Skip to content

Create a JSONP Web Service (in PHP), and Access it via jQuery

July 4, 2010

JSONP is the way in which javascript AJAX applications can access JSON data OUTSIDE of their current domain name. It works almost identically to a normal JSON AJAX request, except there is an extra GET parameter that must be passed, and the requested web service must conform to the JSONP “protocol”.

Within one of the AJAX JSON-requesting functions in jQuery, you need to pass a URL similar to:

http://mywebservice.com/script.php?callback=?

jQuery is nice enough to replace the “?” with the actual JSON callback function, which is used on the server-side to “authenticate” the request. The callback¬†parameter may actually be anything, but it must be the same as what the web service requires (for example, they might say the parameter is called “jsoncallback” rather than “callback”).

On the server side, we must format the JSON output string a certain way as to “authenticate” the request, and to tell the requesting client that it is free to proceed with parsing the JSON string. We “authenticate” requests by doing the following:

// (PHP code)

$myArray = array(“test test”, “Hello!”);

echo $_GET[‘callback’] . “(” . json_encode(myArray) . “)”;

What we are doing here is actually outputting the passed callback parameter, and concatenating the JSON string inside of parentheses, resembling an actual function invokation.

I hope this helped!

Connor

Advertisements

From → regular

3 Comments
  1. “What we are doing here is actually outputting the passed callback parameter, and concatenating the JSON string inside of parentheses, resembling an actual function invokation.” — Great words right there; described perfectly.

  2. I loved as much as you’ll receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an nervousness
    over that you wish be delivering the following.
    unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this hike.

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: