Showing posts with label Sample code to get JSON data from server side using AJAX and getJSON function. Show all posts
Showing posts with label Sample code to get JSON data from server side using AJAX and getJSON function. Show all posts

Friday, 21 February 2014

Sample code to get JSON data from server side using AJAX and getJSON function

jQuery.getJSON function :

     The getJSON() method is used to get JSON data using an AJAX HTTP GET request. $.getJSON is shorthand of $.ajax ,  both are same.

Syntax :

$(selector).getJSON(url,data,successfunction(ouput_data,status,xhr)) 

URL  : A string contains url
data : This is option parameter which is used to sent the value to server. 

     Here status and xhr is optional one and output_data contains the value that will be returned back form your server php file.


Sample code  for  $.getJSON() ;

<script>
$(document).ready(function(){
var send_one = "jQuery";
var send_two = "is nice language";          $getJSON("url","first_value="+send_one+"&second_value="+send_tow,function(respond_data){
         
          $.each(respond_data,function(key,value){
               // $.each function is used to split each array value seperately
               $("#myplace").append("Received data : Index "+key+" => value "+value+"....");
               // if can also print the value without using jQuery each function
                    alert("This is my first value =>"+respond_data.sentme_one);
                    alert("This is my second value =>"+respond_data.sentme_two);       
           });
     });
});
</script>

Sample Code for $.ajax() :

<script>
$(document).ready(function(){
var send_one = "jQuery";
var send_two = "is nice language";     
  
    $.ajax({
               url:"url",
               type:"POST", // or get
               data:{ first_value : send_one , second_value : send_two },
               dataType:"json",
               success:function(respond_data){     

                    $.each(respond_data,function(key,value){

                         // $.each function is used to split each array value seperately
                         $("#myplace").append("Received data : Index "+key+" => value "+value+"....");       
                     });//each() end here
          }//success() end here
     });//ajax end here
});
</script>

 Sample php code : server side
 <?php         
     $_temp_one = $_get['first_value'];
     $_temp_second = $_get['second_value'];
          // Creating array value 
     $_arrayval = array("sentme_one"=>$_temp_one,                                        "sentme_two"=>$_temp_second);
     
          // return the value in json format 
       echo json_encode($arrayval);
  ?>


For more Reference :