Tuesday 4 February 2014


Hi friends, I am currently working on mobile app development using HTML,JQuery,CSS and Javascript and here i have faced so many problem while developing it.. So, I like to share with you guys may be it will be helpful for someone..

Difference between JSON and JSONP :

JSON :   This format is used to interchange of data between same domain...You can only use this kind of data exchange within the SAME DOMAIN. It can't be accessed from other domain.In Mobile App development, if we want to access the database from server side, you will face this CROSS DOMAIN ORIGIN problem this is because, the html file will be install in our mobile device when it try to access the server php file it will be considered as other domain for your own server.Solution for this is use
JSONP(padding json data) , it is nothing but altering the JSON  array format by adding this "(" ")" bracket. it look like this
JSONP   :

([{
     "id":"value1",
     "name":"value"
}])

You can get this value by using GET method in your AJAX function.Or the another way for accessing cross domain data by using callback.

SAMPLE EXAMPLE FOR JSON : 
Note:  Before getting into it, you want to be sure on which platform you using for server side db connection.. here, this example is for phpmyadmin .

JavaScript Object Notation : JSON is a specific kind of format that will be sent(echo) from the .php file(server side) when it get executed.

Example for Cross domain :

<?php
mysql_connect("Yourhostname","Username","Password");
mysql_select_db("DBName");
$sql=mysql_query("SELECT * FROM Table_Name");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
echo $callback.'('.json_encode($output).');';
mysql_close();
?>   

Here, the output will be in the form of JSONP array Format.. it should look like
([{
     "id":"value1",
     "name":"value"
}])
You can simply access this value by calling this .php file from your project.

Client side Ajax code :

EXAMPLE 1:Using callback

  $(document).ready(function() {

  $.ajax({  
  url:"http://yoururl/file.php?callback=?",
  type:'GET',
  dataType:'json',
  success:function(out){
  $.each(out,function(ie,value){
   $('#one').append("Output ",value.id);
    });
  }
 }); 

 }); 
EXAMPLE 2: Another way by declaring JSONP dataType :

  $(document).ready(function() {
  $.ajax({   
  url:"http://yoururl/file.php",
  type:'GET',
  dataType:'jsonp',
  success:function(out){
  $.each(out,function(ie,value){
   $('#one').append("output",value.id);
    });
  }
 }); 
 }); 


1 comment: