AJAX form submission using JQuery PHP

AJAX, in simple layman language, is a technique in which data is asynchronously sent to the server-end from the user-end. By this, we mean that the volume of data or number of data sets are absolutely independent.

AJAX datasets have a very loose coupling, so that every transaction or set of AJAX calls on a single webpage are absolutely exclusive.

This helps in retrieving multiple set of AJAX call datasets at the same time without them intervening with each other.

AJAX form submission – the concept

AJAX form submission is really helpful when you want to make your webpage consume less internet bandwidth. Every page navigation initiates an HTTP call to the server, and then it fetches the whole of the webpage including images, CSS, javascript, etc.

This is really painful in terms of the user. Suppose the user is just submitting a short form and a confirmation is enough for him that the data has been successfully stored. Instead, he gets the whole page reloaded and then gets a statement saying that your form was successfully submitted. This is ridiculous because he has to wait for the whole page to load including its data-heavy elements.

AJAX form submission can bypass this pain and make it helpful for the client end user. The user will fill up the form normally just as in other webpages and submit. Unlike websites where the browser starts navigating and travelling to the action page of the form; our code will simply stop the HTTP redirect and just send the dataset to the backend for storage.

This will sharply lower the responds time, because the bandwidth will be saved. The page will remain as it is. Only a part of the webpage will change upon submission to show the confirmation.

So, first of all, let us create a form in HTML. The following snippet is for a simple form creation. Note here, that the action attribute and the method attribute is supplied with a value. However, we will prevent the form submission with the help of JQuery.

Once the user has filled in the data in the form and clicked the submit button, our JQuery code shall be triggered. The JQuery code will start the required steps on the “Click” event. First of all, it will prevent the default HTML submission (see the commented lines in the code snippet to identify the exact line of code).

Then, the JQuery will prepare the AJAX call with the help of the POST method. It is not recommended that you create an individual variable for each form field and then extract its value to be sent to the backend. That is a tedious job. Instead, JQuery has the feature to serialize a form’s data.

Serialization means it will compose all the field names and their respective values into a long string. This can be passed on as a single data.

AJAX form submission is very popular among several websites these days. It reduces response time and bandwidth usage. Web developers love the technique. I am sure you guys liked it too! Do let me know in the comments!