Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form using AJAX and jQuery

It seems like this should be something built into jQuery without the need for more than a few lines of code, but I can't find the "simple" solution. Say, I have an HTML form:

<form method="get" action="page.html">     <input type="hidden" name="field1" value="value1" />     <input type="hidden" name="field2" value="value2" />     <select name="status">          <option value=""></option>          <option value="good">Good</option>          <option value="bad">Bad</option>     </select> </form> 

When someone changes the select field, I would like to submit the form using ajax to update the database. I thought there would be some way to do the following without manually creating the values/attributes, just send them all, like:

$("select").change(function(){     $.get("page.html?" + serializeForm()); }); 

What am I missing?

like image 940
Chris Bartow Avatar asked Jan 08 '09 17:01

Chris Bartow


People also ask

Can we submit form using AJAX?

We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.

What is AJAX form submission?

AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.

What is form submit in jQuery?

jQuery submit() MethodThe submit event occurs when a form is submitted. This event can only be used on <form> elements. The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.


1 Answers

First give your form an id attribute, then use code like this:

$(document).ready( function() {   var form = $('#my_awesome_form');    form.find('select:first').change( function() {     $.ajax( {       type: "POST",       url: form.attr( 'action' ),       data: form.serialize(),       success: function( response ) {         console.log( response );       }     } );   } );  } ); 

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

like image 153
rfunduk Avatar answered Sep 19 '22 01:09

rfunduk