Tuesday, October 22, 2013

Return JSON data from PHP to ajax function of JQuery

Here we are going to look into how to return JSON date from PHP script to AJAX function of JQuery. I think already you are familiar with PHP and AJAX function of JQuery . If not,  I suggest understanding them first before reading this article.
As we are returning JSON data from PHP script, I hope you have basic understanding of JSON too.
A small introduction of JSON:  JSON stands for JavaScript object notation. It is nothing but data representation technique like XML. We can create JSON data in any programming language (almost all any web programming language like asp,php and jsp etc) .
And JavaScript is right choice to parse and manipulate JSON data.
Here we will use ajax function of JQuery to call PHP script and this PHP script will generate a simple JSON data. This JSON data will return to JavaScript method. Then we will parse returned data using JacaScript.
Let’s try this procedure step by step. As we are using PHP script , to run this example you have to configure Apache server in your system. I would recommend you to use XAMPP (for windows) to configure apache and try this example.

Step 1) Configure apache and keep below code in your HTML page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
  // Code using $ as
usual goes here.
                $.ajax({url:"test.php",
                       type: "POST",
                       dataType:"JSON",
                       scriptCharset: "UTF-8",
                       contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                                   success:function(result){
                                   alert(result[0].result);
                                                }
                                 });
 
});
</script>
</head>
 
<body>
<p id="Data"></p>
</body>
</html>
As we are using ajax function , we have to give JQuery plugin in our program. This article uses JQuery plugin from Google’s CDN. So if you want to same CDN , make sure internet is working in your system otherwise you may download Jquery plug-in and host in your system.

Step 2)  Add below code in PHP file.

<?php
                $rows[] = array("result" => 'This is JSON data');
                $json = json_encode($rows);                     echo $json;?>
This PHP code is very simple , simple JSON data is created and using echo $json; statement JSON data will get displayed and will return to ajax function of JQuery.
Here is sample output.