Showing posts with label Sample code to get JSON data from different domain. Show all posts
Showing posts with label Sample code to get JSON data from different domain. Show all posts

Friday, 21 February 2014

Sample code to get JSON data from different domain


jQuery.getJSON function :

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

Syntax :

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

URL  : It 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?callback=?","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+"....");
               // You 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:"GET", 
               data:{ first_value : send_one , second_value : send_two },
               dataType:"jsonp",
               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 jsonp format
     echo $_GET['callback'].'('.json_encode($arrayval).')';
  ?>