PHP – JSON – JQuery (Sweet Combination)
January 16, 2010
This is an article to show you an example of the how the JQuery (AJAX) works with PHP using JSON.
To work with this code you basically need a JQuery library which you will get from http://jquery.com/
First include the jquery.js file in your .htm file as follows
We are using the JQuery(AJAX) to fetch the records from server side using PHP in the form of JSON.
JSON stands for Javascript Object Notation. It is nothing but the way to write the data in some specific format so that you can access easily as follows.
Access firstName from personObject: personObject.firstName
Access city from personObject: personObject.address.city
Now Suppose you need to fetch the records from server side by using asynchronously (AJAX) then it is necessary that they should come in some specific format like JSON.
PHP Code (get_person_details.php) to create JSON object
$personId = $_POST['id'] ;
/* Here write the code for mysql to fetch the record form database and create an array as follows */
$person = array( “firstName” => “Tushar” , “lastName” => “Mahajan” , “address” => array( “city” => “Pune” , “country” => “India”) );
echo json_encode($person);
?>
Now the following JQuery Code create an AJAX request.
var url = “/person/get_person_details.php”;
$.post( url , { id : 12 } , function(data){
// the {data} is now a JSON object that is created by PHP Code.
alert(data.firstName + ” ” + data.lastName);
alert(data.address.city + ” ” + data.address.country );
}, JSON});
});
So by this way you can eaisly acess the data comming from PHP using JSON.