Encoding PHP array into JSON object and parsing it using Jquery.

PHP 5.2 and higher has native support for JSON .  JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.  For more details about JSON ,visit here.

Initially , I had used json only when I was learning javascript libraries  ‘EXTJS‘ and  ‘SmartClient‘ as the datasource  because php array can be easily encoded into json rather using XML.  But in my recent project I was bound to use JSON as the data we required into the array format from the server side script . I used JSON as the data interchange format rather using XML becuase PHP has easy support for the json encoding and decoding and  JSON can be easily parsed using JQuery . I am a huge fan of JQUERY. Its the first javascript library I have been acquainted with and since then I have been using JQuery for my every projects and its a awesome experience and fun . Soon, I will be posting with   JQuery plugin that I had made.

Now ,  lets encode the php associative array into JSON format .

  <?
     $php_array = array ( 'name'=>'Ram', 'address'=> 'Nepal' , 'tel' =>'00000' );//php associative array 
 
     $json = json_encode ( $php_array ) ;
  ?>

Save the above code into file as _ajaxGetJsonData.php .

Subsequently , the variable $json contains the data in the json format i.e

$json => {"name":"Ram","address":"Nepal","tel":"00000"}

Now,  we have half of our job done. Here,  I have used JQuery to parse the Json data .

$(document).ready ( function ()
 
$.getJSON("_ajaxGetJsonData.php",function(json){
 
alert (json.name ) // alerts  'Ram'
alert ( json.address) //alerts 'Nepal'
alert(json.tel ) // alerts 00000.
 
});
 
});

In above code , JSON asynchronous request  will be executed on document ready state.

  • Share/Bookmark
Javascript, Jquery, Php

Comments

One Response to “Encoding PHP array into JSON object and parsing it using Jquery.”

Leave Comment

(required)

(required)