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:

dataType: ‘jsonp’,
data: ‘catid=10’,
url: ‘’,
success: function () {
// do stuff


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

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

{"id": "1", "title": "Post title 1"},
{"id": "2", "title": "Post title 2"},
{"id": "3", "title": "Post title 3"}

Permanent link to this article:

Leave a Reply

Your email address will not be published.