Jquery Remote JSON Request

If you worked with web development or tried to access the remote file using Jquery you may be used the JSON request ($.getJSON). This will work fine when you accessing the file through jquery $.getJSON API locally.

Jquery Remote JSON Request

You can view demo and download how to access the Remote JSON object in Jquery:

Live Demo Download

But when it comes to the remote file it will not work!. The main reason for this is security risk. Due to browser’s Same Origin Policy (more at Wikipedia) most of the ajax requests can’t successfully retrieve the data from different domain, subdomain or protocol.

If you are developing the HTML5 mobile application you need to access the remote server file in order to communicate with the backend. In this article am going to explain you how to access the remote file through Jquery getJSON API. Before that we will list, what are all the topics you will learn at the end of this article-

  • Understand the browser security policy (Same Origin Policy)
  • Access remote file using JSONP
  • Create JSONP object using PHP and MYSQL

Let’s say am developing a mobile application where I need to get data from my MYSQL server. From frontend we need to send request to remote file which will generates the JSON object from MYSQL database (Read my recent post – How to create JSON object from MYSQL database). Finally we will get that JSON object and will be shown in frontend using Jquery.

If you trying to access the file using normal getJSON request mean you will end up with error. So what is the solution? Here I will explain –

Use JSONP to Access remote files

Create a simple HTML5 document like bellow and include the jquery library

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery Remote JSON Request - webinfopedia</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" ></script>
</head>
<body>
<ul class="title"></ul>
</body>
</html>

Create JSONP Object using PHP

Now we are going to create the JSON object from backend in PHP.(Assume that you have database live if not create a database and add some data) Notice that we have to create the JSONP object rather than conventional JSON object. Once you finished, upload it to the remote server.

//Connect MYSQL database - Change the hostname, username and password
$connect=mysql_connect("hostname","username","password");
//select MYSQL database
$seldb=mysql_select_db("Database-Name",$connect);

//Query to pull the data - Change tabale name and field name 
$getdata=mysql_query("select id,title from table_name order by id limit 0,10");

//Create an empty array
$json = array();

//Fetch the data in a loop
while($r=mysql_fetch_array($getdata)){
//Add the fetched vale to $json array
$json[] = $r;
}

//Encode the array to JSON
$json_data=json_encode($json); 

// Content type
header("Content-type: application/json");  

//JSONP - Make it as JSONP object
echo $_GET['callback'] . ' (' . $json_data . ');'; 

Save the file as jsonpobject.php Next we need to use the $.getJSON API to access the remote file which we have uploaded earlier. Two things we need to mention while using getJSON API

  • Use datatype as JSONP
  • Add additional parameter to remote file URL

Jquery call remote JSONP object

Now call the Jquery getJSON API like below-

$(document).ready(function(){
$(function() {  
    //Calling $.getJSON  API
    $.getJSON('http://www.your-website.com/jsonpobject.php&callback=?',  
		  // No additional parameters sent- If you want you can send below  
		{},
		function (data) {  
		 // data is now JSON object instantiated from retrieved info
		 $.each( data, function ( i, val ) {
			//Title 
			var title=val['title'];
			//Insert the data to HTML page
			$(".title").append(title+'
'); }); }) }); });

Now run the HTML file locally. You should get the response from the server. If not alert the errorThrown and you can debug the problem. I have used this kind of cross browser AJAX request for $.getJSON, $.ajax and $.post APIs.

If you have any doubt or query means feel free to start a discussion through comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>