JSON With Javascript and Ajax

Through the article: Understanding JSON and  JSON With PHP we have a better understanding what JSON is, now we’ll dig more deep by learning JSON With Javascript.

I. Javascript Methods for Handling JSON

In Javascript, there are two methods that we can use to work with JSON:

  1. JSON.parse() to convert a JSON string into a javascript object.
  2. JSON.stringify() to convert the javascript object into a JSON string.

Both methods have been supported by most browsers including the old one. The list of supported browsers are below:

  • Microsoft Internet Explorer: starting version 8.0
  • Microsoft Edge
  • Firefox, starting version 3.5
  • Chrome, starting version 4
  • Safari, starting version 4
  • Opera, starting version 11.5
  • Various mobile browsers

All supported browsers listed at: https://caniuse.com/#feat=json

1. JSON.parse()

As the name implies, this method used to parse the JSON string into a javascript object, this object can have either an object data type or an array data type (in javascript the array data type is also an object for example: var arr=new Array;)

1.a. The Writing Rule

The writing rule of this method is:

JSON.parse(text[, reviver]);

The first argument must be a JSON string, for example:

var json_data = '{"user" : "agusph", "display_name" : "Agus Prawoto Hadi", "website" : "Webdevzoom.com"}';
obj = JSON.parse(json_data);

// Javascript Object can only be displayed through the browser's console
console.log(obj);
console.log(obj.display_name);

The result is:

Parsing JSON With Javascript

Parsing JSON With Javascript

In addition to using javascript default method, we can also parse JSON data with JQuery library by using the method $.parseJSON() but this method is now deprecated and doesn’t relevant anymore, because today all browsers support JSON.parse()

1.b. Second Argument: Using the reviver

Reviver is used to manipulate the value (the pair of the JSON key) of the JSON string before it converted to an object. When the reviver is executed, every properties from JSON string will be evaluated inside the reviver.

This reviever is a function that has two arguments. The first argument is the key of the key-value pair, while the rest is the value, just like a function, this reviver can have a return value.

If the reviver doesn’t have a return value or have a return value but with  undefined value, then the properties (key-value pair) will be removed from the JSON object.

For instance:

<script>
  var json_data = '{"user" : "agusph", "display_name" : "Agus Prawoto Hadi", "website" : "Webdevzoom.com"}';
      obj = JSON.parse(json_data, (key,value) => {
                      
        // Manipulate teh website property
        if (key == 'website') {
          value = 'http://' + value.toLowerCase();
        }
        
        // Manipulate the display_name
        if (key == 'display_name') {
          value = value.toUpperCase();
        }
     
        return value;
    }
  );
  console.log(obj); 
  // Result: {user: "agusph", display_name: "AGUS PRAWOTO HADI", website: "http://webdevzoom.com"}
</script>

Reviver can also be written as a separated function, for example:

<script>
var json_data = '["agusph", "Agus Prawoto Hadi", "Webdevzoom.com"]';
obj = JSON.parse(json_data, my_reviver);
    
function my_reviver(key,value) {
    if (key == 1) {
      value = value.toUpperCase();
    }
    return value;
};

console.log(obj);
// Hasil: ["agusph", "AGUS PRAWOTO HADI", "Webdevzoom.com"]
</script>

2. JSON.stringify()

The JSON.stringify() method is used to convert a javascript object into a JSON string. This object can be either an array or an object.

This function is generally used with AJAX, that is when the data sent to another page to be processed later. In addition, it is also used for displaying javascript object data such as using the alert() function or putting object data into HTML elements.

2.a. The Writing Rule

The writing rule is:

JSON.stringify(value [, replacer[, space]]);

The value argument is mandatory while the others are optional.

An example of JSON.stringify() usage:

<html>
  <head>
  </head>
  <body>
    <form action="" method="post" id="input-form">
      <label>Name</label><input type="text" name="name" value="Agus Prawoto Hadi"/>
      <label>Email</label><input type="text" name="email" value="prawoto.hadi@gmail.com"/>
      <label>Website</label><input type="text" name="website" value="Webdevzoom.com"/>
      <input class="offset button" type="submit" name="submit" value="Submit"/>
    </form>

    <script type="text/javascript">
    $('#input-form').submit(function(e){
      e.preventDefault();
      data = {};
      $('input[name!="submit"]').each(function(i, elm) {
        data[$(elm).attr('name')] = elm.value;
      })
      
      json_data = JSON.stringify(data);
      alert(data_json);
      // Send json_data via AJAX...
    })
    </script>
  </body>
</html>

The above script will generate an HTML form with a name, an email, and a website input field. If we submit the form, then the browser will show an alert that contains the input field data as shown below:

JSON Stringify Example

JSON Stringify Example

See the demo here.

2.b. Second Argument: Using Replacer

The replacer works just like the reviver on the JSON.parse()  that is manipulates the initial javascript object before converted into a JSON string. Replacer can be either a function or an array.

Here is a sample of replacer as  a function:

Continuing the previous example, the following script will change the input name value into capital letters.

<script type="text/javascript">
$('#form-input').submit(function(e){
  ...
  json_data = JSON.stringify(data, replacer);
  ...
})

function replacer(json_key, json_value) {
  if (json_key == 'name') {
     json_value = json_value.toUpperCase();
  }
  return json_value;
}
</script>

See the demo here.

If the replacer is an array, then the resulted JSON string contains only the corresponding properties in that array.

For example: continuing the previous example, the following replacer simply take properties that only have key: name or email.

$('#form-input').submit(function(e){
  ...
  json_data = JSON.stringify(data, ['nama', 'email']);
  // The Result: {"name":"Agus Prawoto Hadi","email":"prawoto.hadi@gmail.com"}
  ...
})

2.c. Third Argument: Using space

Space argument used to generate a JSON string in an easy-to-read format. It is for display purpose only, and not recommended in production environments.

The space argument can be spaces or tabs, here’s an example of space argument with tabs:

<script>
var obj = {};
obj.user = 'agusph';
obj.display_name = 'Agus Prawoto Hadi';
obj.website = 'Webdevzoom.com';

json = JSON.stringify(obj, '', '\t');
console.log(json);
</script>

The Result:

{
	"user": "agusph",
	"display_name": "Agus Prawoto Hadi",
	"website": "Webdevzoom.com"
}

II. JSON and AJAX

In javascript, everything associated with JSON mostly involves AJAX, this is because JSON string usually sent to or provided by other pages either pages on the same domain or on different domains.

Note… on the different domains, we can’t easily retrieve the JSON data, we need to do some “tricks”. In order not to make this article too long, We’ll discuss this subject in another article.

To get JSON data through ajax (on the same domain), we can use the default (native) javascript object, e. g. XMLHttpRequest object or use the Javascript library such as jQuery.

To make it easier, in this tutorial we’ll use the jQuery library.

III. JSON and AJAX on The Same Domain

On the same domain, we can easily retrieve JSON data, the following examples show how to retrieve JSON data from a plain text as well as from a database.

1. JSON From Plain Text – With AJAX

JSON in a plain text often found in a configuration file. For example, in the htdocs folder we have a config.php file with the following content:

{
  "site" : 
  {
    "url" : "http://webdevzoom.com",
    "theme" : "clear",
    "path" : "public_html\\wdz"
  },
  "database" :
  {
    "db_host" : "localhost",
    "db_port" : 3306",
    "db_user" : "root",
    "db_pass" : "",
    "db_name" : "wdz"
  }
}

Note: in the above data, I escape the value of the “path” key by adding a backslash to the \ character. Why? because the backslash is a special character so if we want to use it we need to escape it, see the previous article.

Next, to parse that data we create a json-parse-plain-text.html file containing HTML and javascript code look like the following:

<html>
  <head>
    <title>Understanding JSON - JSON From a Plain Text</title>
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
    $.ajax({
      url : 'http://localhost/config.php',
      dataType : 'json',
      success: function (data) {
        console.log(data);
      },
      error: function (xhr, status, msg) {
        alert('Status: ' + status + "\n" + msg);
      }
    })
    </script>
  </body>
</html>

When the above file opened in a browser, then we’ll get the following result:

Parsing JSON String With Javascript - Plain Text

Parsing JSON String With Javascript – Plain Text

Note… note that when we define the dataType property to “json”, jQuery will automatically parse the JSON string into a javascript object, so we don’t need to use JSON.parse() function.

Thus, if the JSON string is invalid, then we’ll get an error, e.g. if the backslash is not escaped, we’ll get an error message like this:

Error While Parsing JSON String With Javascript

Error While Parsing JSON String With Javascript

The error happened because after the backslash, the parser searches for a special character to escape, but doesn’t find it and only finds the character “j” that is not a special character.

2. JSON From Database – With AJAX

Another common practice is creating a JSON string from a database, such as for pagination, multi-level dropdown options, etc…

In this example, we’ll create a dynamic drop-down option from a database data i.e. sub-categories that changes according to the selected category (e.g. on the product input form).

As an example, in a database named store, we have a table named product_category with the following data:

category_id category_name parent
1 Books 0
2 Music & Instruments 1
3 Hobbies 1
4 Computer & Internet 1
5 Programming 1
6 Home & Garden 0
7 Lighting 6
8 Tools 6
9 Bath 6
10 Computer & Mobile 0
11 Software 10
12 Printers & Scanners 10
13 Laptops 10
14 Modems 10
15 Antivirus 11
16 Office 11
17 Operating System 11
18 Image & Video 11
19 Desktop Programming 5
20 Web Programming 5
21 Mobile Programming 5

Next, we create the file category_list.php that generates JSON data which we’ll use to create dynamic subcategories, the PHP script is as follows:

<?php
if (!@$_GET['parent'])
  die;

$conn = mysqli_connect('localhost', 'root', '', 'store');
$query = mysqli_query($conn, 'SELECT category_id, category_name FROM product_category WHERE parent = ' . $_GET['parent']);
while ($row=mysqli_fetch_array($query)) {
	$data[] = array('id' => $row['category_id'], 'name' => $row['category_name']); 
}

echo json_encode($data);

For an example of the result, run this URL into your browser: http://webdevzoom.com/wp-content/demo/json-with-javascript/category-list.php?parent=1

The result is:

JSON Data From Category List Page

JSON Data From Category List Page

Note… The above JSON data are dynamic according to “parent” value on the URL.

Next, we create the file json-local-dynamic.php that contains PHP and HTML script to create a form with a dynamic category dropdown option:

<form method="post" action="process.php">
  <input type="text" name="item_name" value="<?=@$_POST['item_name'] ?: ''?>"/>
  <select name="category[]" class="category">
    <option value="">Category</option>
    <?php
      $query = mysqli_query($conn, 'SELECT category_id, category_name 
                                    FROM product_category 
                                    WHERE parent = 0'
                          );
                          
      while ($row=mysqli_fetch_array($query)) {
        echo '<option value="'.$row['category_id'].'">'.$row['category_name'].'</option>';
      }
    ?>
  </select>
  <input class="button" type="submit" name="submit" value="Submit"/>
</form>

The above code has been simplified, so you’ll find it differ from the original (demo version and download), but both have the same flow of works.

The form looks like the following:

Multi Level Dropdown Options Form

Multi Level Dropdown Options Form

Next, the javascript code we use is:

$('#form-input').delegate('select.kategori', 'change', function(){
  var $this = $(this), 
      current_id =  $this.val()
      url = 'http://webdevzoom.com/wp-content/demo/json-with-javascript/category-list.php?parent=' + current_id;
      
  $.ajax({
    url: url,
    dataType: 'json',
    success: function(obj)
    {
      var content = obj.data,
          new_option = '';
      
      for (k in content) {
        new_option += '<option value="' + content[k].category_id + '">' + content[k].category_name + '</option>';
      }
      
      $new_select = $this.clone().empty();
      $new_select.append(new_option).insertAfter($this);
    },
    error: function(xhr) {
      alert('AJAX Error...' + xhr.responseText);
    }
  });
});

Note: The above script has also been simplified, just to show you how JSON works with AJAX, the full version of the script can be seen in the demo section or downloaded at the bottom of this article.

The working demo of the script can be found on this page or in the demo section at the bottom of this article.

Then, how the above script works?

When we select a category or a subcategory, the next subcategory will also change, some category has only one sub category, while the others have more than one.

3. JSON From Database – Static

In the previous example, when the category or sub-category changed, the application will always request a new JSON data.

In certain circumstances, this will slow down the application and we’ll find it slow in changing the subcategory, so, if the data is not much, we can make it static.

An example of this method (static method) can be found on this page or in the demo section at the bottom of this article.

IV. Conclusion

To parse JSON with Javascript we use the method JSON.parse(). This method has supported by all browsers, so don’t need to use any library help including jQuery.

To create JSON string from a Javascript object, we use the method JSON.stringify() this method has also supported by all browser, so don’t need any help from external libraries.

If the JSON data coming from same domains, then we can easily retrieve it with AJAX, but if it’s come from different domains, then things become complex (we can’t use ajax – discussed here).

Demo page and download file:

Reference:

JSON stringify
JSON Parse

Subscibe Now

Loves articles on webdevzoom.com? join our newsletter to get quality article right to your inbox. Nothing else, just quality stuff!!!

Our Commitment: We respect your privacy, we'll not share your credential to any party

Leave a comment

Like Us

Newsletter

Great information from webdevzoom.com right to your inbox

  1. Understanding JSONP – With Javascript and jQuery Examples

  2. JSON With Javascript and Ajax

  3. JSON From Database – PHP and MySQL

  4. JSON in HTML Document

  5. JSON With PHP – A Complete Guide

  6. Understanding JSON – A Comprehensive Guide

  7. 7 Best Free Online Image Compressor & Optimizer Tools – Compared & Tested

  8. 40+ Modern Free WordPress Themes For Blog in 2017 – Beautiful & Responsive

  9. Understanding Constant in PHP – Updated to PHP 7

  10. Understanding Variable in PHP – All PHP Version