Thursday, 17 December 2015

How to return an PHP array from an AJAX call ?


              Is it possible to return PHP array to front end in Ajax call? Yes, it is possible through JSON.

JSON: JSON stands for Javascript Object Notation, It is a light weight data interchange format
the JSON Format like

{"employees":[
    {"firstName":"Sri", "lastName":"Ram"},
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Krish", "lastName":"Rao"}
]}


In PHP we have pre-defined methods like json_encode() and json_decode() methods. The json_encode method takes the array as input parameter it returns the JSON format data. json_decode method takes the json format and it returns array.
Here we need json_encode method to achieve our goal
example:
arrayreturn_file.php
               <?php 
                    $arr=array(a=>1,b=>2,c=>3);
                    //convert the array to json format
                     print_r(json_encode($arr));
                ?>
The above code return {"a":1,"b":2,"c":3}
Here a,b, c are keys and 1,2,3 are values

ajaxcall.php:
        <script>
             var arr=new array();
             $.ajax({
               url: arrayreturn_file.php,
               type:"POST",
               success:function(data){
                     //parse the json data
                     var arr = jQuery.parseJSON(data);
// through keys we can access the values
alert(arr.a); // return 1
alert(arr.b); // return 2
alert(arr.c); // return 3

                }
             });
        </script>
Note: Instead of JSON we can use XML also,but XML is the old technology than JSON



2 comments: