Usually web servers will send html data to the browser and the rendering engine will start parsing the html code. Nowadays most of the websites work like a web application and will send or receive live data from the server. For this type of interaction, communication of data-structures are required. We all know, the difference between a PHP Array and JavaScript Array is like car is to carpet. So conversion to a common data format is required for this operation. JSON, JavaScript Object Notation, is very light weight and it is globally accepted as a data exchange format. Lets try sending a PHP array from PHP to JavaScript using JSON.
User requests employee information using AJAX and output array describing a employee position and salary will be like this.
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
Now the PHP array is successfully sent from PHP to JavaScript using JSON.
User requests employee information using AJAX and output array describing a employee position and salary will be like this.
$employee = array( "employee_id" => 10011, "Name" => "Nathan", "Skills" => array( "analyzing", "documentation" => array( "desktop", "mobile" ) ) );Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{ "employee_id": 10011, "Name": "Nathan", "Skills": { "0": "analyzing", "documentation": [ "desktop", "mobile" ] } }
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: "employee.php", async: false, cache: false, data: { employee_id: 10011 }, success: function (jsonString) { var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array. });
Now the PHP array is successfully sent from PHP to JavaScript using JSON.
0 comments:
Post a Comment