How to use Jsonp method in JQuery

JSONP is JQuery(JavaScript) method used to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on<script> tags. JSONP is a viable solution for cross-domain Ajax.

JSONP does not work with JSON – formatted results. JSONP to work, Server must reply with JSONP – formatted results. JSONP requires to wrap the JSON response into a JavaScript function call. When you do the JSONP request the query string will set a parameter called ‘callback’ that will tell the server how to wrap the JSON response.

How it works:
JQuery script:

[js]
$.ajax({
dataType: ‘jsonp’,
data: ‘catid=10’,
url: ‘http://remote-domain.com/getdata’,
success: function () {
// do stuff
},
});

[/js]

PHP Code:
The Server Request will need to return the response as JSON with the requested call back.

[php]
$response = json_encode(getPostsAsArray($_GET[‘catid’]));
echo $_GET[‘callback’] . ‘(‘ . $response . ‘);’;
[/php]

Result:
[code]
callback([
{"id": "1", "title": "Post title 1"},
{"id": "2", "title": "Post title 2"},
{"id": "3", "title": "Post title 3"}
]);
[/code]

Permanent link to this article: https://blog.openshell.in/2014/06/how-to-use-jsonp-method-in-jquery/

Leave a Reply

Your email address will not be published.