Check out my latest project: Full Frontal JavaScript Conference

jQuery AJAX'ed forms

Inspired by Dustin Diaz’s AJAX screencast, I thought it was time I made a little more use of iShowU and show how easy, and quick it can be to pile on some AJAX calories to pretty much any form.

The screencast is sans-sound, really just to try to keep my out-going bandwidth down, but I’ve commented along the way so you can understand (…hopefully…) what I’m doing, and why I’m doing it.

Download the QuickTime screencast, 9MB, a little over 10 minutes

If you can’t view the screencast, try DivX Web Player for Windows or the Mac.

You can also have a look the code used in the screencast to have a play or to upgrade.

As always, let me know if you have any questions or suggestions.

Watch out for this gotcha that I just stumbled in to: if your form has an input element with the name 'action', the line url: this.action is going to grab that element, rather than the form's action. Instead, use this.getAttribute('action')

64 Responses to “jQuery AJAX'ed forms”

  1. K, I solved all my problems all by myself. First, using ":input" to yank all the data from the form didnt cut it for me because it doesnt read checkboxs, radio buttons, or select boxes correctly. Also, just using "escape(this.value)" didn't work, because it stripped the "+" signs out. Below is how I reconfigured that part of your script:

    $(':text', this).each(function() {
      var temptext = escape(this.value);
      temptext = temptext.replace("+", "%2B");
      //myFieldsAry.push(this.name + '=' + escape(this.value));
      myFieldsAry.push(this.name + '=' + temptext);
    })
    $(':option-sel', this).each(function() {
      var mySelName = escape(this.value);
      var myTempSelAry = mySelName.split("_");
      // alert(myTempSelAry[0] + '=' + myTempSelAry[1]);
      myFieldsAry.push(myTempSelAry[0] + '=' + myTempSelAry[1]);
    })
    $(':hidden', this).each(function() {
      myFieldsAry.push(this.name + '=' + escape(this.value));
    })
    $(':file', this).each(function() {
      myFieldsAry.push(this.name + '=' + escape(this.value));
    })
    var myFields = myFieldsAry.join('&');

    Later I ran into a new problem, which is that your script is using GET! But we're letting users write stuff! Some of them write a whole lot, which leads to the "414 Request-URI Too Large" error. After panicking for about an hour, I realized it was very easily remedied with a single parameter in your ajax line:

    jQuery.ajax({
      // data: inputs.join('&'),
      type: "POST",
      data: myFields,
      url: this.action,
      timeout: 45000,
      error: function() {
        console.log("Failed to submit - ");
      },
      success: function(r) {
        $('.content').html(r);
      }
    })

    Now everything is working great! I think you should consider making these permanent changes to your code, as I find that they are huge, but easily implemented, improvements.

  2. @Todd - that's not quite right.

    First up, :input does select all the input elements, but if you only want the selected elements, then this may not be for you.

    Second, escape isn't what you want - you want uriEncodeComponent - this will handle the + symbols.

    Lastly, the Ajax hit that includes this.action is wrong, as it will put the input with the id of 'action' from the form, rather than the attribute.

    I suspect most of these issues have been caused by my own original demo, but you can see a working demonstration of all the points I've raised here:

    http://jsbin.com/uholo (to edit: http://jsbin.com/uholo/edit)

    I should add that the data attribute of the $.ajax function, you probably just want:

    jQuery.ajax({
      type: "post",
      data: $(this).serialize(), // assuming this == the form
      url: $(this).attr('action'),
      // ...etc - rest of fields
    });
  3. Remy,
    First the JS Bin is awesome. You are the man!

    Second, I'd never seen uriEncodeComponent before. Thanks for that bit.

    Third, this.action is working perfect for me so far - and I use all kinds of different action urls. Can you elaborate on when it will bust? I notice in my code i use this.action (normal ole jscript) and you refer to $('this').attr('action') which is JQuery code. I've been using this.action to grab the form action url for a long time. I'm inclined to believe you are right but then theres the "if it ain't broke, don't fix it" rule which even overrules advice from superior coders. Heh.

    Thanks for your help, brother!

  4. i need to get the id (?=136) from 1 page (review_image.php) and sent it to another (submitComment.php), then from there upload the database. please help me im new to this. and bin googleing for weeks now.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight