884

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?



1318

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


});

I hope it helps you.

  • 41
    But form.serialize() can't post <input type="file"> in IE – macio.Jun Jan 19 '13 at 19:25
  • 79
    It's better to put this inside $("#idForm").submit(...) rather than $("#submitButtonId").click(...) – Renato Feb 12 '13 at 12:54
  • 73
    Instead of return false you should be using e.preventDefault() to allow further event propagation after your click handler is complete. Using e.preventDefault() will only stop the default action of the Submit button (e.g. to submit the form) but will allow any other events bound to that form to execute. See: fuelyourcoding.com/jquery-events-stop-misusing-return-false – John Kary Jun 3 '13 at 8:06
  • 43
    Instead of specifying the url to your script here you could just use the forms ACTION attribute which is normally specified: var url = $(this).attr('action'); – Bjørn Børresen Dec 17 '13 at 19:36 
  • 30
    Also in this context you can do data: $(this).serialize(), instead of data: $("#idForm").serialize(), which enables us to specify which form in just one location. – beingalex Jul 2 '14 at 14:15