Dynamic Web Development with Ajax, jQuery, and JSONP

Frontend web developers must be somewhat familiar with the jQuery JavaScript library. This open source solution gives birth to a whole new method of coding website animations and effects. I remember first getting started with JavaScript in early 2003-2004 and the field was ripe with great information.

But modern day web developers have access to many more resources and tutorials online. Specifically I’d like to use this article to look into the jQuery.ajax() method for calling asynchronous data without reloading the page. AJAX(Asynchronous JavaScript and XML) was a hot buzzword along with web 2.0 but it has now evolved into a technology which even beginners should understand.

Why Use Ajax?

Not every web application needs Ajax support but it does provide inherent value in most instances. If you don’t need to refresh the page to pull new data why should you? It saves your users a lot of time and you aren’t loading as many resources on each reload.

Developers who were using Ajax before jQuery probably remember the XMLHttpRequest method. This is actually what jQuery uses to call Ajax, but the library has much cleaner syntax and allows for specific callback methods. But in simple terms this object will request data from the same domain and return any format of plaintext.

As you can imagine this is a great way to append new HTML code into your page. But first I should mention there are a few downsides and limitations. Although we live in very modern times some Internet users do keep JavaScript disabled. With no JavaScript your Ajax calls won’t work and the best fallback solution is a typical backend script in PHP or Rails.

Typical .ajax() Syntax

Let’s look now at an example Ajax call and break down the syntax. Note this is only an example so you can’t just copy/paste this into a document and have everything work smoothly. You’ll always need some type of alternate script which is being processed on the backend.

  type: 'POST',
  url: 'ajax.php',
  data: 'q='+q,
  success: function(data){
    // if successful we have return data and do stuff here
  error: function(xhr, type, exception) { 
    // if ajax fails we get an error

The Ajax method is called from anywhere and doesn’t require a selector in the document. You can have all these parameters on a single line but it’s easier to read when broken down into sections. Let me try explaining each of these pieces in detail. You can get more info at the jQuery.ajax docs.

The type parameter can be set to GET or POST, which are the typical data transfer methods on any server. When using Ajax it really doesn’t matter all that much but I stick to POST since that is how most of my backend scripts are created. The url should target the script you’re accessing via Ajax. In this case I’ve created a file ajax.php in the same directory – this PHP script can do anything from pulling info out of a database to simply outputting “Hello, world!”.

Now the data value should be setup to pass data from your frontend JS into the backend(PHP, ASP, RoR). I’m using a variable q which you could set to any value. An example is pulling the text from a search box and passing that into a backend script for autosuggest functionality.

After the call is processed there are two success and error functions which have code to execute based on the performance of our Ajax call. On success we get some data returned back from the server and we can do whatever with that info. Or on failure we get some error codes back from the server, and these can be useful for debugging. It’s all fairly easy to setup and you’ll learn a lot with even 30-60 mins of practice time.

So What is JSON?

The acronym JSON stands for JavaScript Object Notation. It’s not actually a new language since JSON is still written in JavaScript. But it’s a type of open return data much like XML which you can parse through. Many open online APIs will use JSON as the standard return type instead of XML because it is more compatible with JavaScript. Let’s look at some example JSON data below:


Typically the content will be escaped with forward slashes but you can render these out quickly. It’s popular for developers to store this type of data into a file such as data.json and read/write based on the application. Data caching within JSON is popular since the language has gathered a lot of traction.

The greatest value offered by JSON comes as a return type from 3rd party websites. APIs are a method for you(the developer) to access database information from huge companies like Facebook or Instagram without ever touching SQL code. JSON makes return data that much more manageable and it’s honestly an easier solution than XML in most instances.

Differences Between JSON and JSONP

There is another big topic called JSON with Padding, or JSONP. This returns the exact same JSON data from a 3rd party server but wrapped in a callback function. Why would this be useful you’re asking? Well it gives you the option of using AJAX without pulling the script from your server.

Most scripts do not allow cross-domain access for security reasons. JavaScript is a rare exception that grants you access to 3rd party websites and access to their return data. But when pulling an external URL the page will often just return JSON data with the content-type application/json.

By using JSONP you can wrap the JSON data into a callback function such as myCallback({ "json": "foo" }). A typical JSON API request may look like http://www.devgarage.com/api/json but when JSONP is available for return you would add a callback method. So your new API URL may look like http://www.devgarage.com/api/json?callback=myCallback.

In short JSONP allows you to execute Ajax requests from other domains! You can access an API endpoint and return the data to a callback function you’ve already written. Then inside that function work with the data and append it into your HTML where necessary. I have read some fantastic questions regarding JSON and JSONP differences which clearly illustrate the benefits and possible security risks.

You should notice that not all API providers will allow JSONP. It’s still being adopted into mainstream and web technologies are changing so quickly these days. But the concepts of building dynamic web applications using Ajax and JSON/JSONP is revolutionary compared with older development models.

Additional Reading

Final Thoughts

This topic includes a long list of ideas which you probably cannot digest in one sitting. I hope this article can behave as a resource turning developers onto other ideas they didn’t know about before. I’ve also included some links above which you can check out to learn more information.

As a web developer myself I have to say this topic is not for the light hearted! Ajax requests and working with XML/JSON data will require practice. Reading to learn and understand is one part of the process, but don’t be afraid of getting messy. You can practice simple requests using webapps like jsFiddle and move into your own mini server environments with Koding or Cloud9. Keep yourself busy practicing and before you know it Ajax requests will become like second nature.