jQuery AJAX submit form

Nathan H picture Nathan H · Dec 25, 2009 · Viewed 2.1M times · Source

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?

Answer

Alfrekjv picture Alfrekjv · Aug 5, 2011

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.
           }
         });

    
});