PHP json_encode and jQuery json

Ajax requests using jquery is pretty easy. All you have to do is to specify the URL for request, data sent along with the request, the data type returned, and the callback function. I choose datatype json because it’s much easier to modify with javascript. Here is the example:

Your PHP script, located at http://your/url/to/php/script/:

$array = array(
  'name' =>; 'alex',
  'fruit' =>; 'apple'
echo json_encode($array);

Your javascript Script, with jQuery supported:

  {your: data_to_send}, // ignore this for now
  function(returned_data) {
    //do something with the data returned
    console.log(; // will output 'alex'
    console.log(returned_data.fruit); // will output 'apple'

It won’t output anything on the page, but in the Javascript console instead. Firebug and Webkit-devtool users can see the console output using the “Inspect Element” tool. As far as I know, IE8-9 also has developer tools (press F12), as well as Opera Dragonfly.

Leave a Reply

Your email address will not be published. Required fields are marked *

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