You are here

Creating JSONP data source with Drupal

Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

When creating applications for mobile phonesit is often required that data be read from a remote data source (from a server). When using web-based technologies JSON (JavaScript Object Notation) data format is often applied for data exchange between the client and the server. If your website wants to get some data from the server without reloading the entire page an ajax request using some JavaScript code will do the trick. If the data source is accessible on the same domain name as the website the JSON data format is adequate.

Though if the data source is accessible on a different domain that the website or we want to access it not from a website but from a mobile application, the JSON based data communication will not work (for security reasons a JSON data source can only be accessed on the same domain name).

For this problem the JSONP (JSON with Padding) based communication can be the solution. For example a JSON datra request could look like this:

The response from the server:

    "Name": "Foo",
    "Id": 1234,
    "Rank": 7

The same request using JSONP:

The respons (generated by a server side script, using the value of the callback parameter):

    "Name": "Foo",
    "Id": 1234,
    "Rank": 7

Serving JSONP data with Drupal

I have created a new content type on the installed Drupal 7 website with the required fields and added some examle content. To produce the JSONP content, the following extra modules are needed:

We have to enable the Views, Views UI, Chaos Tools and Views JSON modules.

Create a new view with the required data and choose the "JSON data document" format!

Now you can see the following preview while editing the view:

This is a correct output in JSON format, it seems to be appropriate. But if we save the view and visit the url referring to it this is what we get:

On the one hand you should see only the pure JSON output without the regular components of the theme, on the other that's only a JSON format date, not JSONP. To solve these problems we need to check the format settings of the view:

I put "callback" in the JSON prefix field and swiched off the "Views API mode" option.

If you complete the url of the view with ?callback=jsonCallback at the end you can get the followings:

This output is finally approptiate.

In the application we can process the JSONP data source like this (the actual application is based on PhoneGap, using jQuery and it puts one field of the data source in an unordered list; the list has an id parameter with the value of remote-data):

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.