How to parse json with jquery and ajax

How to parse json with jquery and ajax

In my last tutorial I have explained how to read and write json file with with php and mysql, In this tutorial I am going to explain how to parse json with jquery and ajax and display the output on browser. Since I am using ajax which means only a part of the section will be loaded not the full page, which is a very common and useful technique in web development.

View Demo
Let’s get started. I are going to use the same database from the last tutorial. Please read the last tutorial before (how to read and write json file with with php and mysql) as I am going to be more specific on jquery and ajax. I am going to use two methods viz $.ajax() and $.getJSON() to demonstrate the parsing of json. Use only one at a time not both.

Setup your html first

As I am going to use two different methods $.ajax() and $.getJSON(), I will use them on different click events say fetchMethod1() and fetchMethod2(). Both are used to parse json, I am just showing different ways to do similar things. You can use whichever you find easier.

<!-- getjson function -->
<a href="javascript:void(0);" title="fetch data using $getJSON() method" onClick="fetchMethod1();" >
  <img src="images/button1.png" alt="fetch data using $getJSON() method" width="220" height="50"> 

<!-- ajax function -->
<a href="javascript:void(0);" title="fetch data using $ajax() method" onClick="fetchMethod2();" >
  <img src="images/button2.png" alt="fetch data using $ajax() method" width="220" height="50">

<!-- this is optional to remove the current output !-->
<a href="javascript:void(0);" title="reset" onClick="javascript:$('#output').slideUp('slow');" >
  <img src="images/button3.png" alt="reset" width="100" height="50">

<!-- the container where the output will be displayed -->
<div id="output"></div>

Parsing json using $.getJSON method

Place a button that calls the function named fetchMethod1() which internally calls $.getJSON() function which again calls php page fetch-json.php asynchronously and finally the output sent by this page is displayed on the browser. I have also added an additional feature search records by products name, to demonstrate the working of query string. 

function fetchMethod1() {
	var str = '';
	var qs = $.trim( $("#q").val());
	$('#output').html('<img src="images/loading.gif" alt="" width="143" height="93">').show();

		// for caption and search box
		s = '<div class="caption">This data is fetched by $.getJSON() method.</div>';
		s += '<div style="width:100%; text-align:center;">';
		s += '<div class="height10"></div>';
		s += '<label>Search product by name: <input type="text" name="q" value="" id="q" /></label> <input type="button" value="search" onClick="fetchMethod1();" />';
		s += '<div class="height10"></div>';
		s += '</div>';

		 showOutput(result, s);

Sending and revieving the json through php file

I have named the php file as fetch-json.php. which will fetch records from database , encode the results in json and then it will return the results back to the jquery function.

// configure.php contains basic database connection script
$str = ($_REQUEST["q"] <> "" ) ? " AND products_name LIKE :pname" : "";
$sql = "SELECT products_id, products_name, products_quantity, products_model, 
		products_price, products_weight, products_status 
		FROM tbl_products WHERE 1 $str ";

try {
    $stmt = $DB->prepare($sql);
    if ($str <> "") {
        $stmt->bindValue(":pname", "%" . trim(($_GET["q"]) . "%"));
    $results = $stmt->fetchAll();
} catch (Exception $ex) {

$returnArray = array();
if (count($results) > 0) {
    foreach ($results as $rs) {
        $returnArray[] = $rs;

echo json_encode($returnArray);

So by now you have the json in the function and the only thing left to do is to parse it down and display it on the browser. To make things easier I have created a function named showOutput() which takes two parameter, first the json and other is for caption and search field.
function showOutput(resultData, caption) {
	var str = '';
	str += '<div class="caption">'+caption+'</div>';
	str += '<table class="bordered">';
	if (resultData.length > 0 ) {
		$.each(resultData, function(key, value){

			if (key == 0) {
				str += '<tr>';
				str +=  getColumns(value, "key");
				str += '</tr>';

			if( $.type( value ) == "object") {
				str += '<tr>';
                                // get the fields 
				str +=  getColumns(value, "");
				str += '</tr>';


	} else {
		str += '<tr><td>no records found!</td></tr>';

	str += '</table>';
	// Add some animation effects


There is also a function getColumns() that will parse the json into columns/fields for the table.
function getColumns(obj, toPrint) {
	var v = '';
	$.each(obj, function(key, value){
		if (toPrint == "key") {
			v += '<th>'+key+'</th>'
		} else {
			v += '<th>'+value+'</th>'
	return v;

Parsing json using $.ajax method

This is an alternative to $.getJSON() method. Unlike $.getJSON(), ajax function accepts some parameters to make it work . Check it out below. The rest of parsing and displaying the output are the same.

function fetchMethod2() {

	var str = '';

		type: 'GET', 
		url: 'fetch-json.php', 
		data: { get_param: 'value' }, 
		contentType: "application/json",
        dataType: "json",
		cache :false,
		beforeSend: function () { 
			$('#output').html('<img src="images/loading.gif" alt="" width="143" height="93">').show();
		success: function (data) { 
			 showOutput(data, "This data is fetched by $.ajax() method.");



View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.


Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Guest on

$query = “SELECT * FROM server”;
$result = mysql_query($query);
$dServer = mysql_num_rows($result);

while($row =mysql_fetch_array($dServer))

$dServer = $row[‘model’];


var dServer = ;
var d=parseInt(“dServer”) + “”;


here everything is okk, just parseInt() not converting anything. Could you please explain it?
Or should I use JSON encode ?

Isaac on

The link: how to read and write json using php and mysql points to some other field –>How to search and like friends using faceboook plugins – suff ike that!
Mind correcting that mistake please!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.