Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to process JSON data using Ajax and jQuery?

In this article we will see how to use all the features of JSON with Ajax and jQuery to perform asynchronous calls.

When we transfer data between browsers and servers, it must hold a certain meaning. As such, data needs to be given certain value, such that it can be considered as meaningful information. In order to describe the data that is generally exchanged on the Internet, a specific standard, in the form of a language, has been developed by the World Wide Web Consortium. This is what we call as the Extensible Markup Language or XML.

What exactly is JSON?

JSON, also expanded to Java Script Object Notation, happens to just be another alternative to the widely prevalent XML, which is used to describe data structures. It was first derived from the popular scripting language known as JavaScript.

The use of JSON allows us to interchange useful information between the web applications and their server counterparts. Much like Extensible Markup Language (XML), JSON carries out similar functions and has proven to be very useful. It is also readable by humans, hierarchical in nature and can be parsed using a number of popular programming languages that are in widespread use. This makes it readily available.

Why choose JSON over XML?

JSON offers certain advantages when compared to XML. First of all, JSON is more light-weight in nature than what XML is. In fact, JSON requires fewer tags and you can name a tag just once, unlike XML that requires opening and closing tags. Secondly, JSON happens to be the quicker of the two, thus reducing lag and thirdly, it is also very appealing and a lot more readable, which isn’t exactly the case when one is using XML.

Also, all of these are just additional advantages offered by JSON, without compromising on the functionalities that are offered by XML.

What is Ajax and jQuery?

Asynchronous JavaScript and XML, abbreviated as Ajax, is basically a web development method that is primarily utilized in the client side for the creation of asynchronous application in the Web. Such applications can receive and send data without compromising on behavior and display of a page. Using this technique, data can generally be exchanged without the requirement of having to undergo entire reloading of a page.

jQuery, on the other hand, happens to be a JavaScript library that can be used across multiple platforms and is specially designed to simplify the HTML scripting process on the client-side. It also happens to be the most popular JavaScript library that is used in the world at present.

What shall we demonstrate in this tutorial?

In this tutorial, we will make use of JSON data that is generated using PHP and then display the values in separate elements making use of jQuery Ajax techniques.

However, before we just step into the tutorial portion, let us just see an example, which makes use of both XML and JSON styles.

Structure when using XML

Listing 1: A sample XML file

 <posts>
 
 <title> XML Demonstration </title>
 <url> https://en.wikipedia.org/wiki/XML</url>
 
 <title>jQuery & Ajax Demonstration</title>
 <url>jquery-and-ajax.html</url>
 
 </posts>
 

Structure when using JSON

Listing 2: A sample JSON file

 {"posts": 
  [
  { 
 "title":"Demonstration of JSON", 
 "url":" https://en.wikipedia.org/wiki/JSON" 
 }, 
 { 
 "title":"jQuery and Ajax Demo", 
 "url":"jquery-&-ajax--demo.html"
 }, 
  ]
  }
 

As you can see above, XML and JSON is fairly the same, although different in their syntactical structures.

A JSON syntax usually will look something like this:

jQuery.getJSON( url, [ data ], [ pass(data, txtStat, demo) ] )

In the above statement,


  • url – This will basically be a string that contain s the URL to which one needs to send a request
  • data – This is the string that will be sent to the server along with the request
  • pass(data, txtStat, demo) – This is nothing but a callback function that is executed is the request is successful.

First method using getjSON

 $.getJSON("processdata.php", function(response) {
  $('#result').html(response.first);
  $('#result2').html(response.second);
  $('#result3').html(response.third);
  });
 

The use of this method is to obtain encoded JSON data from a certain server that you are communicating with. In order to so, the method makes use of the GET HTTP request. By making use of JSON data structure, the above given example, simply looks to set the content of some particular elements with values of JSON.

Second method that utilizes jQuery and Ajax

Listing 3: A sample jQuery and Ajax usage

 jQuery.ajax({url: " processdata.php", dataType:'json', success:function(response)
  {
  $('#result').html(response.first );
  $('#result2').html(response.second );
  $('#result3').html(response.third);
  }
  });
 

As such, this method is also pretty similar to the method that we saw in the first one. It also largely does the job of loading JSON data, which is encoded, from a server, and for the process, the GET HTTP request is used.

However, the implementation of Ajax here means that you can also make use of them to specify a number of additional options before sending the Ajax request. As such, a huge number of additional options are available and can be used as per the needs and requirements of the task at hand.

processdata.php file (PHP)

The primary use of this processdata.php file is to use random strings, which are defined in the array, and then generate JSON encoded data from them.

Listing 4: A sample PHP file

 <!--?php <br ?--> //Contains list of string arrays
  $newarry= array("String one, mmmmmmmmmmmm.", "ssssss, fffffff.", "ffffff, ggggggg.","frffffff.", "refrfrfrfrf, ffrfrfrrf. ", "jdfjhekdjn.","String three, llllllllll", "jhdgwdjbwedbw", "String two. xxxxxxxx.","jwdwjehdkwejdnw.", "jnbedjwbedkwjebd", "edwedwedwedwed. kmknuhnde.");
  //Here we are randomizing the strings
  $randomizeone = array_rand($newarry);
  $randomizetwo = array_rand($newarry);
  $randomizethree = array_rand($newarry);
  //Prepare the array output
  $newvals = array('first'=>'1.'.$newarry[$randomizeone],'second'=>'2.'.$newarry[$randomizetwo],'third'=>'3.'.$newarry[$randomizethree]);
  //This is to encode the array with PHP json_encode and print the output
  echo json_encode($newvals);
  ?>
 

JSON data

Given below is the JSON data that is very similar to exactly what the processdata.php file is deemed to generate.

 {
  "first":"1.String two.",
  "second":"2.String three",
  "third":"3.String one"
  }
 

Making use of both the methods (entire code)

The complete HTML code is given below and it shows both the methods, which are wrapped in functions, and then button click events have been implemented to call them.

Listing 5: A sample complete file

 <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">// <![CDATA[
  $(document).ready(function() {
      $("#method1").click(function() {
      MethodOne();
      });
      $("#method2").click(function() {
      MethodTwo();
      });
  });
  //This is Method 2
  function MethodTwo()
  {
      jQuery.ajax({
      url: "processdata.php",
      dataType:'json',
      success:function(response)
      {
          $('#result').html(response.first );
          $('#result2').html(response.second );
          $('#result3').html(response.third);
      }
      });
  }
  //This is Method 1
  function MethodOne()
  {
  $.getJSON("processdata.php", function(response) {
          $('#result').html(response.first);
          $('#result2').html(response.second);
          $('#result3').html(response.third);
      });
  }
  // ]]></script>
  <input id="method1" type="button" value="Json Method One" /><input id="method2" type="button" value="Json Method Two" />
  <div id="result"></div>
  <div id="result2"></div>
  <div id="result3"></div> 
 

Fixing JSON errors that are common found

Often, there are certain common errors that coders tend to make while using JSON. These have been outlined below for your perusal and might need taking care of.


  • Use the correct JSON format. This applies especially for the JSON that is returned by PHP.
  • Instead of using $.getJSON, a more favorable option is to utilize $.get. Often, the $.getJSON might not result in the return of correct JSON, since your php might not be doing so.
  • Always make sure to check the data that is being returned. This can be done by alternating the data.

Conclusion

In the above tutorial, we have shown how to display JSON data by making use of jQuery and Ajax. JSON can be a great alternative to XML, and that will remain no secret, once you go through the tutorial. It is simply a fast and reliable option with fewer hassles.

The code snippets given above clearly explain the methods along with the accompanying descriptions that will help you gain a better idea.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login