Submitting a form as an AJAX request using jQuery

It is often the case where you have a form in your HTML, and you want to submit either all or part of it via AJAX, rather than via standard HTTP GET/ POST.

You can easily do this in jQuery using the serialize() method, which, when called on a jQuery object containing either a form element or form controls (<input />‘s, <select>‘s etc.), will return a URL-encoded string.

Example HTML:

<form id="the-form">
    <input name="username" type="text" value="mattlunn" />
    <input name="password" type="password" value="pass1234" />
</form>

Example JavaScript:

alert($('#the-form').serialize()); // username=mattlunn&password=pass1234 

Try it yourself in this jsFiddle.

This URL-encoded string can be used directly as the GET query string, or as your POST body, so all that is left is to construct a jQuery AJAX request, passing this string as the content of the request:

jQuery.ajax({
    url: '/some/endpoint.php',
    method: 'GET',
    data: $('#the-form').serialize()
}).done(function (response) {
    // Do something with the response
}).fail(function () {
    // Whoops; show an error.
});

You might find this snippet of jQuery code a good starting point for implementing AJAX forms on your website. It copies the method and target from the <form /> control, and makes the AJAX request for you.

/**
 * Utility function to help submit forms/ form controls via AJAX.
 * @param selector: Optional. Parameter passed to find() to restrict which elements are serialized. Default is to return all elements
 * @param success: Required. A function to be executed when the AJAX request completes. Arguments are standard AJAX args. 'this' is the form.
 * @param error: Required. A function to be executed when the AJAX request fails. Arguments are standard AJAX args. 'this' is the form.
 */
jQuery.fn.ajaxify = function (selector, success, error) {
    // Handle the optional case of selector.
    if (arguments.length === 2) {
        error = success;
        success = selector;
        selector = undefined;
    }

    return this.on('submit', function (e) {
        // Copy the options from the '<form />' control.
        jQuery.ajax({
            url: this.action,
            method: this.method || 'GET',
            data: (typeof selector === 'undefined' ? $(this).serialize() : $(this).find(selector).serialize())
        }).done(jQuery.proxy(success, this)).fail(jQuery.proxy(error, this));

        e.preventDefault(); // Don't forget to stop the form from being submitted the "normal" way.
    });
};

The above function can be used like so;

jQuery(document).ready(function ($) {
    $('form').ajaxify(function (response) {
        // Handle a successful submission
    }, function (xhr, error) {
        // Handle an error'd submission
    })
});

If you’re interested in reading further, you may want to check out the definition for a “successful control”; as only these types of elements will be contained in the string returned by serialize(). Furthermore, you may also want to checkout the jQuery plugin “forms”, which is a plugin designed to bring unobtrusive AJAX to your forms.

jQuery delay() not working for you?

jQuery’s delay() function causes more than its fair share of problems over on Stack Overflow. You often see people trying to use delay() to delay something like* setting a CSS property (via css()), and then wondering why their CSS property updated immediately; irrespective of their use of delay().

$('#some-element').delay(5000).css("backgroundColor", "red"); // this won't work

*: Other common problems originate from trying to perform DOM manipulation (via the likes of append(), after() etc, or the setting of HTML/ values (via html(),text() or val()).

The short answer is to basically use setTimeout() instead. The long answer involves looking more into how jQuery queues these requests, and finding out exactly what delay() does…

Why it doesn’t work…

When you call delay(5000), what you’re actually doing is calling delay(5000, "fx") as the function has an optional second parameter (the queue name you wish to delay operation of) which defaults to fx. The various effects methods (fadeOut(), animate() etc.) all use this queue which is why delay() has an effect on them.

However nothing else in jQuery does (by default at least, but we’ll get to that part shortly). That is to say that calls to any manipulation functions (html(), append(), css() etc.) will completely ignore your delay() call, because they’re are all executed immediately, and not queued at all.

How you can fix it…

The recommendation here is to use setTimeout() instead; your code will end up looking like this:

setTimeout(function () {
    $("#some-element").css("backgroundColor", "red");
}, 5000);

However, if you wish to use delay(), you can use the queue() function to queue something. The signature of the queue() function is as follows;

queue([queueName,] functionToBeExecuted(next));

That is to say, the first argument is the name of the queue you wish to add to (which defaults to fx when not specified), and the second argument is the function you wish to queue. That function gets passed one parameter, which you must call when your function has finished doing whatever it needs to do; this is to ensure the next elements in the queue get executed as well.

Therefore we end up doing something like this;

$('#some-element').delay(5000, "my-queue").queue("my-queue", function (next) {
    $(this).css("backgroundColor", "red");
    next();
});

Note that in the above example, we’ve specifically avoided the fx queue; the changing of the background-color is not related to fx at all, so we shouldn’t abuse the use of that queue. Having said that, there are times when queuing to the fx queue is useful; such as when you want to perform an action after a list of effects have completed;

$("#some-element").fadeIn(200).animate({
    padding: "+=50"
}, 1500).delay(1000).queue(function (next) {
    $(this).css("backgroundColor", "red");
    next();
});

Of course, if we wanted to be very explicit about which queues we were using, it’d look something like this:

$("#some-element").fadeIn(200).animate({
    padding: "+=50"
}, 1500).delay(1000, "fx").queue("fx", function (next) {
    $(this).css("backgroundColor", "red");
    next();
});

For further reading after finishing the article, consider reading the delay() documentation or the Stack Overflow question that triggered me writing this article!

Event Delegation with jQuery

This is the last in a series of posts on bubbling, delegation and how to delegate events with jQuery. You should already have read the articles What does event bubbling mean and Event Delegation in JavaScript, or have a grasp on their topics.

Event Delegation with jQuery

At the end of the last post, we had a table with hundreds of rows. Each row contained a <a /> to which we wanted to attach a click handler to. We added a single handler to the <table/> element (we delegated the event handler to it) to capture the event.

The correct way to delegate an event handler to the <table> for a click on the <a /> in jQuery would be;

$('#the-table').on('click', 'a', function (e) {
    alert('You clicked row #' + $(this).closest('tr').prop('rowIndex')); 

    e.preventDefault();
});

See it in action here. In words, we capture the element we wish to delegate the event to ($('#the-table')) and call the on() method on it. The event type is the first parameter (click), and the second parameter is a selector which pinpoints the descendant(s) we wish to handle events for (a). The third parameter is the event handler.

Inside the event handler, this is the element the event occurred on (e.g. the <a /> that was clicked). Inside the Event object;

  1. e.target is the element the event occurred on (the same value as this).
  2. e.delegateTarget is the element the event is delegated to (the <table /> element).

Note that jQuery has the same caveat as normal JavaScript when delegating an event to an element; the element you’re delegating to (the table in this case) must exist in the DOM at the time you attach the event.

Controlling Event Bubbling with jQuery

A developer can prevent an event bubbling any further up the list of ancestors if they want to.

To do this, call the stopPropagation() on the event object passed to an event handler. This will execute all other event handlers bound to the current element, but will not propagate up the DOM. You can see this in action here. Even though we’ve bound a click handler to all elements in the ancestor chain, you only see alerts for the a, span and h1, as the h1 handler prevents the event bubbling further.

stopImmediatePropagation() will also prevent the event propagating, but it’ll also stop any other event handlers bound to the current element from firing.

You can check whether an event’s had it’s propagation stopped via the isPropagationStopped() method and isImmediatePropagationStopped() methods.

Another way a developer can stop the event propagating is by returning false from an event handler. This is equivilant to calling stopPropagation() and preventDefault(). I personally recommend against using this shortcut, as it’s use can cause confusion; instead use the methods themselves to make your code more meaningful.

Event Delegation in JavaScript

This is the second post in a series on bubbling, delegation and how to delegate events with jQuery. It assumes you’ve already read the first post What does event bubbling mean, or already have a grasp on event bubbling in JavaScript.

Event Delegation

When providing examples, I’m going to refer to the HTML we used as an example in the first post (shown below):

<div>
    <h1>
        <a href="#">
            <span>Hello</span>
        </a>
    </h1>
</div>

Also note that I’m still not interested in adding support to older versions of IE (<9). You’ll have to add the normal fallback to attachEvent instead of addEventListener if you want to support them, and find an alternative for querySelector/ querySelectorAll. The event target property exists as srcTarget in older versions of IE.

So now we understand event bubbling… but how does it help us?

It means if we want to add an event handler for a click on the <span> element in the above example, we don’t need to add it to the <span> element; we can add it to any of it’s ancestors… as shown here;

window.addEventListener('load', function () {
    document.querySelector('div').addEventListener('click', function (e) {
        if (e.target.nodeName === "SPAN") {
            alert('Click event fired on the SPAN element'); 
        }
    }, false);
});

But yes, I hear you ask me again… how does this help us?

Imagine you have a table with hundreds of rows. Each row contains a <a /> to which you want to attach a click handler to. With no event-bubbling you’d have to bind the event handler to each <a />; which involves iterating over each element and adding an event handler individually to each one. See it in action here. Does it feel efficient to you?;

window.addEventListener('load', function () {
    // Add loads of rows
    var rows = '';

    for (var i = 0; i < 100; i++) {
        rows += '<tr><td>' + i + '</td><td><a href="#">Click Here</a></td></tr>';
    }

    document.querySelector("table").innerHTML = rows;
    // End setup

    // Attach event to each element
    var elements = document.querySelectorAll('#the-table a');

    for (var i=0;i<elements.length;i++) {
        elements[i].addEventListener('click', function (e) {
            alert('You clicked row #' + this.parentNode.previousSibling.innerText);
        }, false);
    };

    alert('Event handler bound to ' + elements.length + ' elements');
});

Instead, what we could do is bind one click handler to the <table />.

document.querySelector('#the-table').addEventListener('click', function (e) {
    if (e.target.nodeName === "A") {
        alert('You clicked row #' + e.target.parentNode.previousSibling.innerText);
    }
});

See this in action here.

Secondly, imagine you load some content dynamically and you want some capture some events on it. You can only add event handlers to elements once they exist (makes sense right?), so without event-bubbling you’d have to re-bind the same event handlers to your content each time you add the content.You can see this in an example here, where we add rows to the table programmatically when you click a button.

However, because the <table /> element does exist in the DOM when the page is rendered, we can add an event handler to this no problem, as shown here. This is a common problem when loading elements via AJAX as well; and attaching the event handler to an element that is in the DOM from the page load is the solution.

So in summary, you should be taking advantage of event bubbling by using event delegation if you want to handle an event for multiple elements, or you want to bind events to dynamically loaded data.

Now move onto the next article; Event Delegation with jQuery

What does “event bubbling” mean?

“Delegation” and “bubbling” are terms that gets thrown round a lot in JavaScript; but what exactly do these terms mean?

This is the first in a series of posts on bubbling, delegation and how to delegate events with jQuery; What does event bubbling mean, Event Delegation in JavaScript and Event Delegation with jQuery

Event Bubbling

In JavaScript, events bubble. This means that an event propagates through the ancestors of the element the event fired on. Lets show what this means using the HTML markup below;

<div>
    <h1>
        <a href="#">
            <span>Hello</span>
        </a>
    </h1>
</div>

Lets assume we click the span, which causes a click event to be fired on the span; nothing revolutionary so far. However, the event then propagates (or bubbles) to the parent of the span (the <a>), and a click event is fired on that. This process repeats for the next parent (or ancestor) up to the document element.

You can see this in action here. Click “Hello” and see the events as they get fired. The code used is shown below;

window.addEventListener("load", function () {
    var els = document.querySelectorAll("*");

    for (var i = 0; i < els.length; i++) {
        els[i].addEventListener("click", function () {
            alert('Click event fired on the ' + this.nodeName + ' element');
        });
    }
});

Note that I’m not interested in adding support to older versions of IE (<9). You’ll have to add the normal fallback to attachEvent instead of addEventListener if you want to support them, and find an alternative for querySelectorquerySelectorAll.

That’s all event bubbling is; an event fired on an element bubbles through its ancestor chain (i.e. the event is also fired on those elements). It’s important to note that this isn’t a jQuery feature, nor is it something that a developer must turn on; it’s a fundamental part of JavaScript that has always existed.

Ok, that’s a little bit of a lie… sort of.

By default, not all events bubble. For instance submit does not normally bubble, nor does change. However, jQuery masks this in the event handling code using all sorts of voodoo, so it will seem that they do bubble when using jQuery.

Now move onto the next article; Event Delegation in JavaScript