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

Category: jQuery

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


(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) {

' + 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



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 + '');
Published:' + item.pubDate + '');

' + 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

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

I am currently working on developing an iPhone app for Northwest Nazarene University. Part of this app will need to connect to the school’s webserver to retreive items such as news feeds and shared photo galleries. Being primarily a web developer I have turned to two projects created by Nitobi persons, PhoneGap and jQTouch.

PhoneGap allows me to use my current HTML, CSS, and Javascript knowledge to build a site. Then using the PhoneGap xcode project I simply drop the web files into a directory and PhoneGap transforms them into a glorious iPhone app.

jQTouch is a jQuery based library that makes the app look and feel like a real iPhone app.

This setup worked beautifully until I needed to connect to the school’s webserver and retreive content. I began to run into cross site scripting (XSS) headaches. After days of pounding my head into my desk I ran across a neat little feature in Apache that allows you to turn off the XSS protection on the server. You may be thinking that sounds insecure, and you would be right, but if you are trying to pull content off your server with Javascript from remote locations it may be just the thing you need to get it working. This does not come built in Apache, it is a module you have to add in. It was pretty trivial. Here are the directions for setting up mod_headers in Ubuntu

To check and see if mod_headers was actually loaded save the following to a PHP file and view it from the server in your browser


If that was successful mod_headers should be listed. You can now move on to the more fun stuff.

There are two ways in which you can allow XSS. The first is through a .htaccess file. This method works great, however it enables XSS for all files in the directory. The second is through PHP header(). The PHP method allows you to target more specifically what files are XSS capable, and even would allow you to do some other safety checks in your code before setting the XSS header.


Header add Access-Control-Allow-Origin "*"


header('Access-Control-Allow-Origin: *');

Another thing to take note of is the *. The * means anyone from anywhere may do XSS. You can however specify specific hosts that have access. See the link at the bottom of this post for more information on that.

Congratulations! You should now have an XSS compatible website. Make extra sure that all of your security is in place because XSS opens up a whole new can of worms for crackers. Ensure all input from users is cleaned before it touches your database or anything else remotely sensitive.

Articles that helped me along the way:
Access-Control-Allow-Origin Multiple Origin Domains?
Configure Apache To Accept Cross-Site XMLHttpRequests on Ubuntu
HTTP Access Control
Server-Side Access Control
Social Javascript (cross-site ajax)

jQuery: Selecting only the first level children

Warning: DOMDocument::loadHTML(): Unexpected end tag : pre in Entity, line: 14 in /srv/users/serverpilot/apps/benlobaughnet/public/blog/wp-content/plugins/auto-amazon-links/amazon.php on line 78

Using the .not() operator with jQuery it is possible to select only the first level of children of an element. This could come in handy on a menu for instance. Let’s see what the menu code looks like.

  • Item
    • Sub
    • Sub2
    • Sub3
  • Item2
  • Item3

We are trying to get ul li, but not ul li ul li. jQuery has a brilliant method to select page elements like so:

$('ul li')

However this will get ALL of the li elements not matter the depth. We only want the first level of li. Luckily jQuery again has a method to accomplish this using .not()

$('ul li').not('ul li ul li')

Voila! We now have only the first level of li elements

jQuery: Detect enter key

Sometimes it is nice to be able to detect when the user has pressed the enter. This is great for super custom forms and Javascript games. Or maybe a totally custom built app that is waiting for the user to hit enter for some reason. But how to detect the enter key? Luckily jQuery once again comes in handy. Check out the following bit of code to grab the enter key.

$('#keyed_element').keyup(function(e) {
    if(e.keyCode == 13) {
        // Put your key handler code here

jQuery: Oh How I Love Thee

I started using jQuery last week and I am finding it to be a great library so far. It is very easy to interact with elements on the page in fun and creative ways.

As a sample, I have been working with the Northwest Nazarene University web team and they wanted to develop a simple wizard they can put on any page that will help prospective students find the degree they are interested in. I decided to tackle that task. At first I was looking at slide show sample, then one of the other developers showed me the beauty of .load(), which allows me to load into any arbitrary element the contents of any file or web address. After playing with .load() and the event handlers for an hour I figured out a way to implement what they wanted. It took me maybe 4 hours going from ground zero of no knowledge on the subject to implementing a working system complete with calls to a backend PHP file that gets the contents for the wizard from the database. jQuery is really neat, I highly encourage other web developers to check it out. A working sample may be found here or on NNU’s website.

Here is the jQuery code I used. Try not to be too critical, I am positive there has to be a better way of doing this. I still am learning the vast amount of options available to me in jQuery.

Powered by WordPress & Beards