MOCKSTACKS
EN
Questions And Answers

More Tutorials









Jquery Using Ajax to Submit a Form


Sometimes you may have a form and want to submit it using ajax.

Suppose you have this simple form -

<form id="ajax_form" action="form_action.php">
 <label for="name">Name :</label>
 <input name="name" id="name" type="text" />
 <label for="name">Email :</label>
 <input name="email" id="email" type="text" />
 <input type="submit" value="Submit" />
</form>


The following jQuery code can be used (within a $(document).ready call) -

$('#ajax_form').submit(function(event){
 event.preventDefault();
 var $form = $(this);
 $.ajax({
 type: 'POST',
 url: $form.attr('action'),
 data: $form.serialize(),
 success: function(data) {
 // Do something with the response
 },
 error: function(error) {
 // Do something with the error
 }
 });
});

Explanation



var $form = $(this) - the form, cached for reuse.

$('#ajax_form').submit(function(event){ - When the form with ID "ajax_form" is submitted run this function and pass the event as a parameter.

event.preventDefault(); - Prevent the form from submitting normally (Alternatively we can use return false after the ajax({}); statement, which will have the same effect)

url: $form.attr('action'), - Get the value of the form's "action" attribute and use it for the "url" property.

data: $form.serialize(), - Converts the inputs within the form into a string suitable for sending to the server. In this case it will return something like "name=Bob&email=bob@bobsemailaddress.com"



Conclusion

In this page (written and validated by ) you learned about Jquery Using Ajax to Submit a Form . What's Next? If you are interested in completing Jquery tutorial, your next topic will be learning about: Jquery All in one examples.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.