In this tutorial you are going to see, how to parse JSON data that is coming from a PHP file in jQuery.
If you already know how to read data from a PHP file using jQuery AJAX, it will be the same concept with an extra jQuery function called $.parseJSON()
First, we create a PHP file to print a sample JSON result (data.php).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $data = array( "a" => "one", "b" => "two", "c" => "three", "d" => "four", "e" => "five" ); $encode = json_encode($data); echo $encode; ?> |
The output of the above PHP code will be a JSON result like below:
1 |
{"a":"one","b":"two","c":"three","d":"four","e":"five"} |
And, here is the second PHP file with jQuery Ajax function which will execute the data.php and print result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<html> <head> <title>Basic JavaScript Form Validation - Tutorialsmade.com</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $( function(){ //on click of the button $( '.btn' ).click(function(){ //get the json data from data.php $.get('data.php', function( res ){ //parse the result using $.parseJSON() jquery function parsedRes = $.parseJSON( res ); //use the key to print the values respectively $( '.a' ).text( parsedRes.a ); $( '.b' ).text( parsedRes.b ); $( '.c' ).text( parsedRes.c ); $( '.d' ).text( parsedRes.d ); $( '.e' ).text( parsedRes.e ); }); }); }); </script> </head> <body> <h3>Parse JSON result in jQuery - <a href="http://www.tutorialsmade.com/learn-parse-json-data-jquery"> Tutorialsmade.com</a></h3> <button class="btn">Click to get Result from data.php</button> <h4>Result</h4> <table> <tr><td class="a"></td></tr> <tr><td class="b"></td></tr> <tr><td class="c"></td></tr> <tr><td class="d"></td></tr> <tr><td class="e"></td></tr> </table> </body> </html> |
Read the comments in the above script to understand it.
In the above script $.get method is used to call data.php and $.parseJSON() to parse the JSON result. See line no. 13, parsing the data, and from the line no. 16 to 20, using the appropriate keys to print the values.
Here is the online demo of this example: