1017

I have a form with name orderproductForm and an undefined number of inputs.

I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.

I suppose one way would be to do something like

jQuery.get("myurl",
          {action : document.orderproductForm.action.value,
           cartproductid : document.orderproductForm.cartproductid.value,
           productid : document.orderproductForm.productid.value,
           ...

However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Nathan H
  • 44,105
  • 54
  • 154
  • 235

20 Answers20

1534

This is a simple reference:

// this is the id of the form
$("#idForm").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');
    
    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    
});
Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
Alfrekjv
  • 15,448
  • 1
  • 11
  • 4
  • 55
    But form.serialize() can't post in IE – macio.Jun Jan 19 '13 at 19:25
  • 4
    Great answer for normal form submission! – The Sheek Geek Feb 04 '13 at 21:36
  • @alex Yes. It should't be any problem (Maybe some differences if your're using `this`) – Renato Feb 21 '13 at 18:49
  • The downside of this is that the ajax will only work when the form is submitted by clicking the submit button, not when the enter key is pressed. Also the URL is hardcoded into the JavaScript. – superluminary May 08 '13 at 10:01
  • what to do if I want to send form name and also submit button in ajax Submit – Shivek Parmar Sep 07 '14 at 18:37
  • can the url called come from an "http" or does it have to be local? your example: var url = "path/to/your/script.php"; – Papa De Beau Feb 05 '15 at 02:22
  • hey @Alfrekjv I am just revisiting this, great job btw, but I have a question. Is it possible to pass a function like "document.GetElementById['label'] = "some words"; " into the data and then use it as a function. – Cornelis Apr 19 '15 at 04:21
  • 2
    Similar to @BjørnBørresen, you can also use `type: $(this).attr('method')` if you use the `method` attribute on your form. – djule5 Oct 06 '15 at 18:51
  • He never said he wanted a submission button with it, nor did he say he wanted it to run live, so how do you know he has a submit button? – i am me Oct 16 '15 at 17:20
  • 3
    Might be worth mentioning that the since jQuery 1.8, .success, .error and .complete are deprecated in favor of .done, .fail and .always. – Adam Jun 06 '16 at 16:38
  • `$("#idForm").serialize()` won't work for file inputs. Use `FormData` instead when dealing with file inputs. – Noopur Phalak Sep 21 '16 at 12:43
  • 2
    @JohnKary's comment - great article, looks like it's no longer available though. Here's an [archive of **jQuery Events: Stop (Mis)Using Return False**](https://web.archive.org/web/20160603125641/http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/) – KyleMit Nov 17 '16 at 15:58
848

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

AjaxForm:

$("#theForm").ajaxForm({url: 'server.php', type: 'post'})

or

$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})

ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

Serialize:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theForm').serialize())

AJAX serialization documentation is here.

K DawG
  • 11,686
  • 9
  • 28
  • 63
jspcal
  • 47,335
  • 4
  • 66
  • 68
  • 2
    interesting idea, however, i do not control the server side I am calling, therefore I cannot send it serialized data – Nathan H Dec 25 '09 at 01:45
  • 26
    Yes you can, the name isn't important what it will do is send pairs of every form-key and every form-variable. –  Dec 25 '09 at 01:50
  • 7
    It's serialized into a query string, just like the data you are putting into the array manually in the GET call there would be. This is what you want, I'm pretty sure. – JAL Dec 25 '09 at 01:50
  • 1
    oooh I see, I then add this string to the end of the URL in the get call. I was thinking PHP serialize. Sorry. Thanks! – Nathan H Dec 25 '09 at 01:56
  • 246
    `.ajaxSubmit()`/`.ajaxForm()` are not core jQuery functions- you need the [jQuery Form Plugin](http://jquery.malsup.com/form/) – Yarin Jun 05 '12 at 02:58
  • Does this work with submitting the form to external sites i.e. cross domain requests? What if I have multiple forms - Can it do multiple form submits? – oneiros May 11 '13 at 04:02
  • It can be done with multiple form submits. I've done for my site. – ipkiss Feb 06 '14 at 14:18
  • jQuery Ajax Form worked great! I arrived here because I was having issues with Ruby on Rails' built in AJAX library was not working as expected. I was able to work around the Rails issue by using this library instead! – danielricecodes Apr 29 '17 at 17:35
  • i can't get JQuery Ajax Form to work, with the syntax in the answer i get "unexpected :" while with the example in the link i don't get my post values in my server.php – Fuseteam Jul 24 '20 at 15:39
474

Another similar solution using attributes defined on the form element:

<form id="contactForm1" action="/your_url" method="post">
    <!-- Form input fields here (do not forget your name attributes). -->
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>
nyedidikeke
  • 5,016
  • 7
  • 33
  • 49
Davide Icardi
  • 10,707
  • 7
  • 51
  • 67
  • Any suggestions on how to do this if the name attribute includes a "."? (Server-side requirement, not my idea). – Josef Engelfrost Nov 29 '13 at 08:11
  • Include an error callback to this to make it complete. One never knows when one will get an error, should always account for it. – aaron-coding May 15 '15 at 18:30
  • 1
    If you don't set method or action, they default to `get` and the current URL respectively. Could do with adding this assumption to the code. – rybo111 Jun 05 '15 at 15:02
  • 1
    Per jQuery documentation (https://api.jquery.com/submit/), frm.submit(function(event){..}); is equivalent to frm.on("submit", function(event){..});. To me latter is more readable as it is obvious that you are attaching an event handler to an element to be executed when event is fired. – mehmet Nov 29 '15 at 20:53
  • @rybo111 - In the console I can see data getting serialized, but not posting. Can the **url** be the problem? My form statement goes like this: `
    `
    – user12379095 Jun 27 '20 at 18:07
  • @user12379095 Yes, you need to set the URL of where you want to post to. – rybo111 Jun 28 '20 at 08:05
  • @rybo111 - Which URL would that be? I have a form (generated with an FBV) where I have gathered the inputs. Now to save the data, I have created another FBV and created URL in the root `urls.py`. In my Ajax function should I point to this URL? Could you please point me in the right direction? – user12379095 Jun 28 '20 at 08:59
  • @user12379095 Yes, `action`'s value should be the URL to where your form posts its data to. – rybo111 Jun 28 '20 at 11:57
179

There are a few things you need to bear in mind.

1. There are several ways to submit a form

  • using the submit button
  • by pressing enter
  • by triggering a submit event in JavaScript
  • possibly more depending on the device or future device.

We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.

2. Hijax

The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.

We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.

3. Unobtrusive JavaScript

Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.

Speed

We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.

Code

Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:

$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});

You can manually trigger a form submission whenever you like via JavaScript using something like:

$(function() {
  $('form.my_form').trigger('submit');
});

Edit:

I recently had to do this and ended up writing a plugin.

(function($) {
  $.fn.autosubmit = function() {
    this.submit(function(event) {
      event.preventDefault();
      var form = $(this);
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize()
      }).done(function(data) {
        // Optionally alert the user of success here...
      }).fail(function(data) {
        // Optionally alert the user of an error here...
      });
    });
    return this;
  }
})(jQuery)

Add a data-autosubmit attribute to your form tag and you can then do this:

HTML

<form action="/blah" method="post" data-autosubmit>
  <!-- Form goes here -->
</form>

JS

$(function() {
  $('form[data-autosubmit]').autosubmit();
});
superluminary
  • 38,944
  • 21
  • 142
  • 143
  • 2
    how can I add the callbacks to 'done' and 'fail' functions? something like $('form[data-autosubmit]').autosubmit().done(function({ ... }); This is possible? – Crusader Feb 17 '14 at 01:54
  • 1
    Hi @Crusader - certainly, instead of having this plugin return this, you could have it return the ajax event, then you could chain right onto it. Alternately you could have the plugin receive a success callback. – superluminary Sep 07 '15 at 11:17
  • I don't see how does this " .. leave it submittable if JavaScript fails" happen here? – mehmet Nov 30 '15 at 11:12
  • @mmatt - If JavaScript is disabled, the form is still just a form. The user clicks submit and a regular browser based form submission occurs. We call this progressive enhancement. It's not such a big deal nowadays since modern screen readers support JavaScript. – superluminary Nov 30 '15 at 11:22
  • @mmatt - The promise callbacks will optionally receive a parameter which contains the data. – superluminary Nov 30 '15 at 11:40
  • Question to the above answer: Would not the use of success: function(data) be better than the .done() as the former has wider range of use since it gives you the returned data (e.g., one such use could be to replace/renew the form -for further submission- if returned with errors from the server)? – mehmet Nov 30 '15 at 11:50
  • This solution seems to submit the form twice and increment exponentially! i did solve that using `event.stopImmediatePropagation(); ` This will stop the form submit twice. – AvikB Dec 12 '15 at 08:20
  • Hi @Avik, Infinite recursion like this usually means you are AJAXing in content from the same URL you are currently on, and appending a page to itself. I'm pretty certain this code will not submit twice. stopImmediatePropagation will disable all other event handlers attached to the form, which suggests you have some other JavaScript going on in there. Might you perhaps have some other code on your page which is submitting the form? – superluminary Dec 14 '15 at 11:39
  • i don't think there is any other code on my page that submit the form(or maybe i missed it :S). Here is a same issue like me. The third answer(the highest voted one) seems to work. [Same issue](http://stackoverflow.com/questions/20195483/jquery-ajax-form-submits-twice) – AvikB Dec 16 '15 at 02:50
46

You can also use FormData (But not available in IE):

var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector        
$.ajax({
    type: "POST",
    url: "yourURL",// where you wanna post
    data: formData,
    processData: false,
    contentType: false,
    error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage); // Optional
    },
    success: function(data) {console.log(data)} 
});

This is how you use FormData.

Mikael Dúi Bolinder
  • 1,963
  • 1
  • 14
  • 34
macio.Jun
  • 8,823
  • 1
  • 42
  • 40
29

Simple version (does not send images)

<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
    (function($){
        $("body").on("submit", ".my-form", function(e){
            e.preventDefault();
            var form = $(e.target);
            $.post( form.attr("action"), form.serialize(), function(res){
                console.log(res);
            });
        });
    )(jQuery);
</script>

Copy and paste ajaxification of a form or all forms on a page

It is a modified version of Alfrekjv's answer

  • It will work with jQuery >= 1.3.2
  • You can run this before the document is ready
  • You can remove and re-add the form and it will still work
  • It will post to the same location as the normal form, specified in the form's "action" attribute

JavaScript

jQuery(document).submit(function(e){
    var form = jQuery(e.target);
    if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
        e.preventDefault();
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: form.serialize(), // serializes the form's elements.
            success: function(data) {
                console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
            }
        });
    }
});

I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.

Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.

To support buttons you can capture the actual button click instead of the submit.

jQuery(document).click(function(e){
    var self = jQuery(e.target);
    if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
        e.preventDefault();
        var form = self.closest('form'), formdata = form.serialize();
        //add the clicked button to the form data
        if(self.attr('name')){
            formdata += (formdata!=='')? '&':'';
            formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
        }
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: formdata, 
            success: function(data) {
                console.log(data);
            }
        });
    }
});

On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH for php

PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //is ajax
}
Community
  • 1
  • 1
Timo Huovinen
  • 46,329
  • 33
  • 128
  • 127
22

This code works even with file input

$(document).on("submit", "form", function(event)
{
    event.preventDefault();        
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {


        }
    });        
});
Shaiful Islam
  • 6,448
  • 12
  • 35
  • 54
13

I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.

So here is what I came up with:

;(function(defaults, $, undefined) {
    var getSubmitHandler = function(onsubmit, success, error) {
        return function(event) {
            if (typeof onsubmit === 'function') {
                onsubmit.call(this, event);
            }
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize()
            }).done(function() {
                if (typeof success === 'function') {
                    success.apply(this, arguments);
                }
            }).fail(function() {
                if (typeof error === 'function') {
                    error.apply(this, arguments);
                }
            });
            event.preventDefault();
        };
    };
    $.fn.extend({
        // Usage:
        // jQuery(selector).ajaxForm({ 
        //                              onsubmit:function() {},
        //                              success:function() {}, 
        //                              error: function() {} 
        //                           });
        ajaxForm : function(options) {
            options = $.extend({}, defaults, options);
            return $(this).each(function() {
                $(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
            });
        }
    });
})({}, jQuery);

This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:

 $('form').ajaxForm({
      onsubmit: function(event) {
          // User submitted the form
      },
      success: function(data, textStatus, jqXHR) {
          // The form was successfully submitted
      },
      error: function(jqXHR, textStatus, errorThrown) {
          // The submit action failed
      }
 });

Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.

Community
  • 1
  • 1
BruceHill
  • 6,435
  • 6
  • 55
  • 106
9

I got the following for me:

formSubmit('#login-form', '/api/user/login', '/members/');

where

function formSubmit(form, url, target) {
    $(form).submit(function(event) {
        $.post(url, $(form).serialize())
            .done(function(res) {
                if (res.success) {
                    window.location = target;
                }
                else {
                    alert(res.error);
                }
            })
            .fail(function(res) {
                alert("Server Error: " + res.status + " " + res.statusText);

            })
        event.preventDefault();
    });
}

This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}

You can vary this as you like. Feel free to use that snippet.

Tarion
  • 14,013
  • 11
  • 61
  • 98
  • 1
    What is `target` for here? Why would you submit a form with AJAX, only to redirect to a new page? – 1252748 Oct 14 '14 at 13:01
9

jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button

Please follow steps

Step 1 - Form tag must have an ID field

<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>

Button which you are going to click

<button>Save</button>

Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.

$("#submitForm").submit(function(e) {
    e.preventDefault();
    var frm = $("#submitForm");
    var data = {};
    $.each(this, function(i, v){
        var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });
    $.ajax({
        contentType:"application/json; charset=utf-8",
        type:frm.attr("method"),
        url:frm.attr("action"),
        dataType:'json',
        data:JSON.stringify(data),
        success:function(data) {
            alert(data.message);
        }
    });
});

for live demo click on below link

How to submit a Form using jQuery AJAX?

7

I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input"); 
let formData = new FormData(); 
for (let input of formInputs) {
    formData.append(input.name, input.value); 
}

fetch(form.action,
    {
        method: form.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));
Alain Cruz
  • 3,588
  • 3
  • 17
  • 31
6

Try

fetch(form.action,{method:'post', body: new FormData(form)});

function send(e,form) {
  fetch(form.action,{method:'post', body: new FormData(form)});

  console.log('We submit form asynchronously (AJAX)');
  e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
    <input hidden name="csrfToken" value="$0meh@$h">
    <input name="email" value="aa@bb.com">
    <input name="phone" value="123-456-666">
    <input type="submit">    
</form>

Look on Chrome Console > Network after/before 'submit'
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
5

consider using closest

$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
        frm = $(ev.target).closest('form');
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert(data);
            }
        })
        ev.preventDefault();
    });
test30
  • 2,920
  • 28
  • 24
5

You may use this on submit function like below.

HTML Form

<form class="form" action="" method="post">
    <input type="text" name="name" id="name" >
    <textarea name="text" id="message" placeholder="Write something to us"> </textarea>
    <input type="button" onclick="return formSubmit();" value="Send">
</form>

jQuery function:

<script>
    function formSubmit(){
        var name = document.getElementById("name").value;
        var message = document.getElementById("message").value;
        var dataString = 'name='+ name + '&message=' + message;
        jQuery.ajax({
            url: "submit.php",
            data: dataString,
            type: "POST",
            success: function(data){
                $("#myForm").html(data);
            },
            error: function (){}
        });
    return true;
    }
</script>

For more details and sample Visit: http://www.spiderscode.com/simple-ajax-contact-form/

roberrrt-s
  • 7,249
  • 2
  • 41
  • 53
suresh raj
  • 61
  • 1
  • 3
4

To avoid multiple formdata sends:

Don't forget to unbind submit event, before the form submited again, User can call sumbit function more than one time, maybe he forgot something, or was a validation error.

 $("#idForm").unbind().submit( function(e) {
  ....
4

If you're using form.serialize() - you need to give each form element a name like this:

<input id="firstName" name="firstName" ...

And the form gets serialized like this:

firstName=Chris&lastName=Halcrow ...
Chris Halcrow
  • 21,541
  • 11
  • 115
  • 145
2

This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.

var $form = $('<form/>').append(
    $('<input/>', {name: 'username'}).val('John Doe'),
    $('<input/>', {name: 'user_id'}).val('john.1234')
);

$.ajax({
    url: 'api/user/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    data: $form.serialize(),
    success: function(data, textStatus, jqXHR) {
        console.info(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        var errorMessage = jqXHR.responseText;
        if (errorMessage.length > 0) {
            alert(errorMessage);
        }
    }
});
wonsuc
  • 2,284
  • 17
  • 25
2

I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:

$('form#foo').submit(function () {
    $.ajax({
        url: 'http://foo.bar/some-ajax-script',
        type: 'POST',
        dataType: 'json',
        data: {
            'foo': 'some-foo-value',
            'bar': $('#bar').val()
        }
    }).always(function (response) {
        console.log(response);
    });

    return false;
});

Then, in the backend:

// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
Lucas Bustamante
  • 11,643
  • 6
  • 66
  • 74
  • OP said he doesnt know the field names / undetermined so one can't use data in this instance as one doesnt know the field names. – SupaMonkey Sep 11 '20 at 08:28
2

JavaScript

(function ($) {
    var form= $('#add-form'),
      input = $('#exampleFormControlTextarea1');


   form.submit(function(event) {

       event.preventDefault(); 

       var req = $.ajax({
           url: form.attr('action'),
           type: 'POST',
           data: form.serialize()
       });
    req.done(function(data) {
       if (data === 'success') {
           var li = $('<li class="list-group-item">'+ input.val() +'</li>');
            li.hide()
                .appendTo('.list-group')
                .fadeIn();
            $('input[type="text"],textarea').val('');
        }
   });
});


}(jQuery));

HTML

    <ul class="list-group col-sm-6 float-left">
            <?php
            foreach ($data as $item) {
                echo '<li class="list-group-item">'.$item.'</li>';
            }
            ?>
        </ul>

        <form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
            <p class="form-group">
                <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
            </p>
            <button type="submit" class="btn btn-danger">Add new item</button>
        </form>
Marty
  • 41
  • 5
-24

There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.

examples

Souad
  • 3,981
  • 10
  • 58
  • 118
billw
  • 91
  • 2