I think, therefore I am. I am, therefore I sail

Retrieve remote JSON content with jQuery

I am currently working on an iPhone app using the PhoneGap project as a base. PhoneGap allows me to use my current web development knowledge to develop an application using HTML, CSS, and Javascript. A key component in almost all iPhone applications is retrieval of remote content. I am going to walk you through the steps I took while developing the iPhone app for Northwest Nazarene University.

For ease of development purposes I have downloaded the jQuery library, version 1.4.2, to my local machine.

Let’s start by creating a basic HTML file that we will manipulate as we go.

We could statically build our own JSON string here, but since we are building an app to retreive remote content why don’t we use an external source. There is a weather module in the NNU iPhone app that will do nicely. You can find it here http://www.nnu.edu/iphone/api/weather.php (No longer online 🙁 ) and the output should look something like

{"temp":["70"],"condition":["Fair"]}

(At the time of writing this was correct, but the site is still in development and may change slightly)

Great, we have our source, now we need to pull the content from it. Luckily jQuery provides some handy tools for grabbing remote content, and specifically for JSON data. Here is where the first trick comes in, cross site scripting (XSS). XSS happens when a Javascript service attempts to pull content from another server. XSS has been used for malicious purposes in the past and is therefore tightly controlled. jQuery is supposed to be able to legitimately access remote content, but if you are having problems see my post Enabling XSS for iPhone apps with PhoneGap and jQTouch to learn how to configure your Apache server to allow the remote pull.

Let’s see what the jQuery code looks like

$.getJSON('http://www.nnu.edu/iphone/api/weather.php', function(data) {
  $('body').html('

' + data.temp + '

'
    + '

' + data.condition + '

');
});

Using $.getJSON we can provide a callback for the returned JSON. I am going to use a dynamic function in this example, however you can also point it to a function name you define elsewhere. See http://api.jquery.com/jQuery.getJSON/ for more information regarding the $.getJSON function.

After previewing the index.html file in your browser you should see

73

Fair

Congratulations, you have successfully pulled remote JSON into your app!

You can download the complete source code here

Complex Objects
Let’s take it a step further now and work with some complex objects. We will be using the NNU iPhone app’s JSON news feed located here http://www.nnu.edu/iphone/api/rssproxy.php?url=nnu_news (No longer online 🙁 ). I am not going to post the JSON string because it gets quite long. You can view it by loading that URI into your browser.

Again, create your initial basic HTML index file. We will reuse the one listed in the above section.

Now the code for this section is going to be a little more intense. The object we are getting back contains multiple array of information. We will need to loop over the array in order to grab the individual news elements and display their contents. jQuery provides us with the $.each function (See http://api.jquery.com/each/) which we can hand the JSON data off to and get to the good stuff. Let’s see what this code will look like

$.getJSON('http://www.nnu.edu/iphone/api/rssproxy.php?url=nnu_news', function(data) {
        $.each(data, function(i,item){
                $('body').append('' + item.title + '');
                $('body').append('
Published:' + item.pubDate + '');
                $('body').append('

' + item.description + '


');

        });
});

If everything was written correctly you should now see a listing of the news items when you refresh the index.html file in your browser.

You can download the full source here

Having Trouble?
If you are receiving a denied error from the server, or a 200 success message with no content you may be experiencing cross site scripting (XSS) issues. Take a gander at my post Enabling XSS for iPhone apps with PhoneGap and jQTouch to prevent this behavior in the future

Previous

PHP+Apache: Enabling XSS for iPhone apps with PhoneGap and jQTouch

Next

PHP: Downloading remote content with CURL

13 Comments

  1. Apologies for the stripped p tags. If this page generates a lot of traffic I will fix it.

  2. Rod

    Hi, just found your tutorial while I googled for phonegap json. I was just wondering have you ever run into any issues with running into problem in the simulator. I am new to Javascript and jQuery. I have created a login system that works correctly in safari. It involves using getjson to retrieve several fields from the database associated with a validated login. When I ran through the simulator, nothing happens with the submit button. Would be grateful if you could share your experience.

  3. Rod,

    I want to first make sure we are talking about the same simulator. There are two, the first is the iPhone simulator that is used in XCode for the PhoneGap project, and the other is a simulator that has been released by the nice people at Nitobi. I have run the code in both and it works fine. If it works in desktop Safari it “should” work on Mobile Safari as well.

    How are you accessing it with your Javascript? Do you have a code sample you could share? How is your server sending it out? I actually set the headers manually in PHP to be JSON. Is it possible that your server is erroring and you cannot see the error because of your remote call? Check your log files. Also, if your development code is on the same server as your remote content is pulling from there will be no cross-site scripting issues (XSS), however when you run the simulator your server may be interpreting it as XSS (though getJSON is supposed to prevent that) and not allowing the content to be sent out. In which case you may want to look at my post on enabling XSS.

    Take a look at that and post another comment with your findings.

  4. Sam

    Thanks for sharing this, it’s exactly the kind of example I was looking for and very clearly written. Really useful to read your link on enabling XSS for apps too.

    Off to xcode to test 🙂

  5. sushrut bidwai

    If the control of server is with you then cross site scripting is not an issue. But if you are working with some public api and then run into the issue? I think most apps which publish a public api should take care of setting up there servers to allow for cross site scripting right?

    • sushrut bidwai,

      Yes, servers offering public APIs should have this stuff setup properly already. Using $.getJSON should work out if they do not have a proper setup, but if they do not their service might be a little shady

  6. This post is pure gold. I wish it ranked higher in Google’s results. You rescued me! Thanks

  7. Peter

    Hi.
    What about a
    server running .net and serving XML content.

  8. Peter,

    Take a look at using jsonp for that:
    http://api.jquery.com/jQuery.ajax/

  9. Kalor

    That nuu site is dead, so I tried my own service. My URL is fine (the server is being hit), but I don’t get anything on the android emulator screen.

    • Yes, unfortunately after sitting on it for a year without actually releasing the app they seem to have dropped it.

      Try your URL in FireFox with FireBug. If you see the correct output then the issue resides with your display code. If not you may want to look at my cross site scripting post to see if that is the issue.

  10. I downloaded and opened the index.html in chrome. It showed “Page Content Here”.Can you tel me why?

    • Nope, it probably has something to do with Chrome. Since NNU took down that linked file it should not be showing anything

Powered by WordPress & Beards