cult3

jQuery Ajax

Dec 12, 2012

Table of contents:

  1. The Ajax method
  2. Get
  3. Get JSON
  4. Load
  5. Post
  6. Serialize
  7. Conclusion

One of the coolest things about jQuery is how easy it is to use Ajax. Ajax (Asynchronous JavaScript and XML) is a group of technologies that allow you to send and receive data from a server asynchronously (without refreshing the page). Ajax is used extensively around the Internet these days, in particularly on Social Networking websites where updates are automatically pushed to the browser, or where the page infinitely scrolls as long as there is content to view.

Ajax has become one of the fundamental aspects of web applications. Without Ajax, web apps can often feel clunky or dated. Fortunately jQuery makes it really easy to get up and running with Ajax.

The Ajax method

The real main method for making asynchronous requests in jQuery is the Ajax method. The Ajax method allows you to make precise requests if you are trying to do something quite specific. If you are just making generic type requests, you can get away with using one of the simpler methods that I will cover later.

Once you understand the structure of the Ajax method and how it works, you will find that all of the other methods are really quite simple.

There is a lots of different things you can do with the Ajax method, far too much to try to explain in a single blog post. I will cover some of the common things you need to know about the Ajax method, but if you want to do something very specific or under a unique circumstance, take a look at the official documentation.

In it’s simplest form, the Ajax method is simply:

$.ajax();

However in order to make the method useful, we need to pass it a URL to make the request and some settings to tell the method what we want to do. The settings are simply optional key/value pairs.

Load data

The first example we’ll look at is simply loading another HTML page using Ajax. I’m using an HTML page because it’s going to be a really simple starting point just so you can see it in action.

So firstly we need to quickly create two html pages, one called index.html and one called extra.html.

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<div id="results"></div>

extra.html

<title>Hello</title>

hello world

Next we need to write some jQuery for the index page so it will load the extra page into the results div.

$(document).ready(function () {
  $.ajax({
    url: "extra.html",
    success: function (html) {
      $("#results").append(html);
    },
  });
});
  1. First we wrap everything in a document ready block so the jQuery is fired once the page has fully loaded.
  2. Next we need to call the Ajax method
  3. The first key/value pair we need to pass is the url to find the page we want to request.
  4. Next we pass a function if the request is a successful. In this case we pass the HTML we got from the extra page and append it to the results div

See, that was pretty easy, huh?

So in it’s simplest form, the Ajax method is simply a URL to request, and a list of settings depending on what you want to do with the request.

As I mentioned above, there are many different settings that you can use with the Ajax method. I won’t go into every single one of them because in all honesty, you won’t be using them in your day to day jQuery usage. If you stumble upon a situation where you need to do something very specific, the jQuery documentation has a good explanation of each of the different settings. In this tutorial I will be covering some of the more common ones in the rest of the example code.

Get

As I mentioned above, the Ajax method is really the base for all of the other Ajax type method. Why would you not just use the Ajax method? Well, a lot of the types of Ajax requests you will be using don’t need to be over complicated with additional settings. Think of the additional methods as shorthand versions to make the process of making requests simpler.

One of these shorthand methods is the Get method.

Using the same example above, we could of got the same result by using the following:

$.get("extra.html", function (data) {
  $("#results").html(data);
});

So as you can see, we use the Get method and pass it to arguments, the URL to retrieve and a function to be fired if the event was successful.

You can think of the Get method as shorthand for this equivalent Ajax method (where some of the settings are optional).

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType,
});

In the Ajax method above, the data argument would be used if we want to send something to the url, and the datatype would allow us to specify what datatype we expect from the server. In the Get example above, we are not sending any data to the URL and jQuery is intelligent to know that it is HTML that is coming back so we don’t need to specify these settings.

As a bit more of an advanced example, say we wanted to get some JSON from an API. We could use the following Get request:

$.get("api.php", function(data) {
    alert.(data.status);
}, "json");

In this example we are making a request to the api, we expect JSON to be returned and we want to pop an alert containing the status from the data object that was returned.

Get JSON

The Get JSON method is a more specific version of the Get method for getting JSON data in a request.

$.getJSON('api/users.json', function(data) {
    $.each(data, function(key, val) {
        $('ul').append("<li>" + val + "</li>");
});

In this example we are requesting user data from the api. If the request was successful, we then take the returned data and iterate over it using the each method, appending each user to the ul element in the DOM.

You can think of the Get JSON method as being the equivalent to the following Ajax method version:

$.ajax({
  url: url,
  dataType: "json",
  data: data,
  success: callback,
});

Load

The Load method is probably the easiest way to load HTML content into the DOM. Again, the Load method is essentially a stripped back version of a Get request, but it’s syntax makes it much easier to use because you don’t have to explicitly pass a function to put the returned content into the DOM.

For example:

$("#timeline").load("feed/status.html");

In this example, we are getting the contents of the status.html page and inserting it into the timeline element.

You can also pass a callback to be fired once the load is complete:

$("#timeline").load("feed/status.html", alert("Great success"));

If you want to only load a specific part of the HTML, you can pass in a selector. The entire HTML page is still requested, but when it is injected into the DOM, only the selected element will be inserted.

$("#timeline").load("feed/status.html #main");

Post

The Post method is used for sending data through a HTTP POST request. The Post method is very similar to the GET method in that it is essential a shorthand version of the Ajax method with the following settings:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType,
});

When you use the Ajax method without specifying the type, it will default to GET.

The following could be a typical example of a Post request using jQuery:

$.post(
  "/users",
  { name: "Philip Brown", status: "Writing some JS" },
  function (data) {
    $("#results").append("Status updated");
  }
);

After we specify the request URL we must also send some data. In this case I’m sending some simple JSON. If the request was successful, we update the DOM.

Serialize

When you want to send the data from a form using a Ajax request, you need to take the inputed data and turn it into a URL-encoded string.

To convert the data, we can use the Serialize method.

For example:

$("form").submit(function () {
  alert($(this).serialize());
  return false;
});

This would pop an alert with the following string (obviously you would need a form with the appropriate fields to get this result!).

name=philipbrown&location=uk&gender=male&age=24

So a typical example using a POST request could be:

$("form").submit(function () {
  $.post("$('form').attr('action')", $(this).serialize(), function (data) {
    $("form").hide();
    $("#results").append("Status updated");
  });
  return false;
});
  1. First we bind an event to the submit button.
  2. Create a Post method
  3. Grab the action URL from the form
  4. Serialise the content of the form
  5. Hide the form
  6. Update the DOM with a success message
  7. Return false to prevent the form from actually submitting

Hopefully that breakdown should explain what’s going on here. We need to return false on the submit action because the browser will want to actually submit the form to the action URL. We don’t want to actually submit the form, so we can stop that happening from returning false. If the request is successful we can hide the form and update the DOM with a success message. This shows the user the form has submitted correctly, without the page ever having to refresh.

Conclusion

jQuery makes using Ajax within your web applications extremely easy. Ajax has become such a staple part of good interface design, that the lack of it can really date a website. Ajax is perfect for creating rich experiences within the browser and jQuery is the perfect first step towards it.

That was an overview of the most common jQuery Ajax methods that you will come across. In the final instalment of our exploration of jQuery, we will be looking at Effects.

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.