Home > Wordpress Development > Implementing jsonp for cross domain request

Implementing jsonp for cross domain request

Your would be very happy when it comes to crossdomain with ajax call. I have one of the solution to make a crossdomain successful with jsonp.

Problem:

The main problem for making a cross domain request is many browser has a security restriction as we cannot make any request other than the current domain.

Solution:

The solution is jsonp, but you might be thinking how does that work to0?

We all know that javascript can be included with any domain, there is no restriction for that . So we can use the same thing to get our desired output.

I have created a test application in php to give a response to a get request.

$callback_function = $_GET['callback'];</pre>
//some json generated via some logic.
$some_json_string = '{"menu": {
 "id": "file",
 "value": "File",
 "popup": {
 "menuitem": [
 {"value": "New", "onclick": "CreateNewDoc()"},
 {"value": "Open", "onclick": "OpenDoc()"},
 {"value": "Close", "onclick": "CloseDoc()"}
 ]
 }
}}';

//set header as we need to return the javascript
header('Content-type: application/javascript');

//return with a function which was set as a callback
echo $callback_function.'('.$some_json_string.')';
<pre>

Also some javascript code in your html/php file which is on other domain.

jQuery.getJSON('http://crossdomain.com/jsonp.php?callback=?',function(json){alert(json.menu.id);});

You can refer to the following screenshot. You can also check the domain from which i am calling. The domains have been changed via host file.
cross domain jsonp request...
I will be implementing jsonp without getJson method. Hope this will save lot of your time ..

Advertisements
Categories: Wordpress Development
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: