Returning JSON data using jQuery

I started playing with jQuery lately, and I am absolutely pleased with how easy it makes my life and saves me tons of mundane operations. I had to change the way I think about working with AJAX lib’s since I am a long time SAJAX user, but it wasn’t that big of a deal. It took me a second to realize something i want to share with you, and I hope it will help you get started using this great tool.

One thing that makes things way easier is to use Services JSON ( or the PEAR version of it if you have it available ) , to return structured JS objects or arrays back into jQuery.

I would say for $_GET operations use something like this


     $.getJSON("/yourscript.php", ( { val1: value } ),
            function(databack)
             {
                $.each(databack,function(i , val) {
                       alert(i+"="+val);
              });
      });
);

This simple example will send a GET request to “yourscript.php”, with variables val1=value ,which means on the php end you will see this $_GET["val1"] = value.  Because jQuery Ajax call will fetch whatever the output of the php script is , make sure you process and print the desired variable at the end.

What makes your life real easy is using JSON


..... some code 

 $aOut = array("1"=>"One","2"=>"Two");
 $oJSON = new JSON_Services();

 echo $oJSON->encode($aOut);

This will return a well formatted JS object back to JQuery so you don’t have to worry to properly format it on the php end. Once the object is returned, I am using $.each ( or jQuery.each ) , to loop over the object. The result is as expected – “i” would be “1″ , then “2″ , and “val” would be – “One”  and “Two” on the next iteration.

Let’s talk for a second about the second parameter of the $.getJSON function. It’s obvious that this is where it sends the values to the Php script. You can easily fetch a value, for example from an input field using jQuery selectors like this


   $.getJSON("/yourscript.php",
        ( { value: $( "#myfield" ).attr( "value" ) ,
           value2: $( "#myfield2" ).attr( "value" ) } ) ,
      function(databack)
       { ............ }
   );

Leave a Reply