Advertisements
Home > javascript > Simple form submit with jQuery

Simple form submit with jQuery

In building ajax driven apps, one of the things that you have to do is capture form submits, send them to the server, and then handle the results.  In many applications, the results are data, passed as JSON or XML or some other format that the remote service provides.  In other apps, we’re dealing with snippets of HTML that then get placed in the current page somewhere.   I want to be able to handle all forms on the pages, without needing to know in advance how many forms there are, what they are called, what’s in them, or what to do with the results.  I haven’t found a good succinct description of how to do this, so here’s mine using jQuery.  This isn’t rocket science.  Its just pulling together some of jQuery’s nice features.  There are other good ways to do this.

$(document).ready(function(){
    $("form").submit(function(){
         var thistarget = this.target;
         jQuery.ajax({
             data: $(this).serialize(),
             url: this.action,
             type: this.method,
             error: function() {
                 $(thistarget).html("<span class='error'>Failed to submit form!</span>");
             },
             success: function(results) {
                 $(thistarget).html(results);
             }
         })
         return false;
         }
    );
});

This captures all submits on all forms on the page, and uses jquery’s ajax call to post the form’s fields to the URL in the form’s action attribute, and then places the results in the element identified by the form’s target attribute.   You could easily use jQuery.post instead of ajax, and all you would lose is the error message, at least of the options I included above.  jQuery.ajax has a bunch of options, which are documented nicely here:
http://docs.jquery.com/Ajax/jQuery.ajax#options

The forms in the page look like normal forms, and don’t need any special attributes other than that we are abusing the target attribute a little to specify the target element for the results.

<form name=’myform’ id=’myform’ action=’targetURL’  target=’target element’>
First Name: <input type=’text’ name=’firstname’ id=’firstname’>
<input type=’submit’ name=’submit’ value=’Submit’>
</form>
<div id=’target element’></div>

If I submit this form, either using the Submit button or by hitting enter in the firstname field, the fields from the form (in this case just firstname) are posted to targetURL, and if the post works the results that I get back are inserted into the ‘target element’ div.  If the post fails for some reason (for example, if I get back a 404 error or something) then the “Failed to submit form!” message is inserted into the ‘target element’ div.

Note that if javascript isn’t available, the forms will still work.  We’ll just get the results in the named target window instead of having it inserted into the page.

Advertisements
Categories: javascript
  1. WeaponsTheyFear
    December 27, 2009 at 6:48 pm

    Thanks. Every other tutorial I’ve read on doing this seemingly simple task has excluded the error option. I don’t know javascript at all, but almost had it working correctly.

  2. David
    November 5, 2011 at 6:04 am

    Thank You!
    You Forget the o “#” :
    $(“#”+thistarget)
    ?

    • David
      November 5, 2011 at 7:03 am

      Right! If its an ID (which is what I was using in the example), you need the proper selector.

  3. July 9, 2013 at 4:41 am

    Hai;

    Good work.Nice descriptions and explanations.Thank you for sharing this.Can we add the jquery validation to this form submission ?

    • David
      July 9, 2013 at 7:51 am

      The best way to do that is to make the function in this post the callback for the validation plugin’s submitHandler options. In that case, the callback needs to accept a form parameter and use that instead of the selector, so $(“form”) becomes $(form). This prevents the validation from firing again.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: