Ajax forms are the integral part of web technology today. It makes sending HTTP requests very easy, no page reloads and it’s fast, it can send-receive information in a various formats such as HTML, JSON or XML. Let’s learn various ways to send HTML form data using jQuery Ajax.
jQuery has various shorthand Methods to jQuery.ajax(), such as .get(), .post(), .load(), .getJSON(), they all accomplish the same thing, but are more specific to the tasks and require less code.
Lets start off with a simple HTML form, and then we can write jQuery codes for it that perform Ajax requests:
The jQuery snippets below demonstrates ways to submit HTML form.
The .serialize() method serializes a form inputs to query string that could be sent using Ajax.
To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax. Old browsers (eg: IE9) doesn’t support FormData, check caniuse.com for more info.
That’s all the code we need to upload files using jQuery Ajax. The contentType is set to false otherwise default is set “application/x-www-form-urlencoded”, which is no good for uploading files, setting it false will post data as “multipart/form-data”.
Another important thing here is processData, which must also be set to false, otherwise jQuery will try to serialize the FormData object into query string, and you might end up with an Illegal invocation error.
While posting data to server, we can notify user about the progress happening in the background. For that we use xhr callback function.
That’s it, I hope it has provided some insight into jQuery Ajax Form Submit, and will surely come in handy in your future projects. Please do share your feedbacks which will help improve this article further.