Wednesday, October 16, 2013

AJAX - How To Retrieve JSON Response from PHP script

Hello Friends, This is my first tutorial post.

Today I'll explain you how to retrieve JSON response via Ajax call.

First we build a PHP script to send response in JSON format, then we will gather this response from an Ajax call through jQuery script.

Let’s first create a PHP script 

Create a PHP script, I’ll name it as “json_response.php”
And add following code in it



//set header for JSON response
header("Content-Type: application/json");

//render array in JSON format
echo json_encode(array('status' => 200, 'message' => 'Response from PHP script in JSON format.'));

This is a basic example to send JSON response.
PHP script will send response with status code and message.

Now create a HTML file to fetch JSON response and add it in header tag.

Create a HTML file, I’ll name it as “json_response.html”
And add following code.


                                                                                                                           <script src=""></script>                  
        <script type="text/javascript">                                                                                
            $('document').ready(function() {                                                                          
      //create ajax call to fetch json response                                                            
                $.ajax({                                                                                                                          url: 'json_header.php',                                                                                
                    type: 'GET',                                                                                               
                    dataType: 'JSON', // it is necessary to get JSON response                                                                                                         
                    success: function(response) {                                                                      
                       // if reponse status is success                                                                  
                        if (response.status == 200) {                                                            
       // add message to header tag                                                    
        <h1 id="message"></h1>                                                                             
Note: It is very important to add ajax request parameter  dataType: 'JSON' to fetch response in JSON format.

After running HTML file in browser you see the header tag has message as

Response from PHP script in JSON format.

Zainul Abedin Shaikh

Founder of Zainabed, Passionate about programming. Follow him on Twitter

And if you enjoyed this post, please consider sharing it on Facebook, Google+ or Twitter below


Post a Comment