jQuery Ajax Submit Form to Pass Data to PHP File

Last Updated on April 18, 2023 by Roshan Parihar

In this tutorial, learn how jQuery ajax submit form and send your form data to a PHP file. You can submit the form without page refresh using ajax submission. After you send form data to a PHP file, you can use your form data with a PHP script to get the required result.

Ajax helps you refresh a part of a webpage without reloading the whole page. To give immediate results to your users, ajax form submission is the best option for users. You can easily collect form data and process it with PHP script without the need to refresh the whole page.

How jQuery Ajax Submit Form and Send Data to PHP File

To create jQuery ajax form submission and pass the required form data to a PHP file, you have to create an HTML file, JS File, and PHP File with the codes given below.

HTML Code (form.html)

First of all, create an HTML file with the name ‘form.html’ and add your form as given below. The form contains the input type text field, input type email field, and textarea field. You also have to place a submit button for form submission.

The action attribute should contain the PHP file (post.php) where you have to pass the form data on submission. The below example shows the HTML form with all the required fields.

The above HTML code also contains the <div id="data"> element to display the result below the form.

jQuery Ajax Code (jquery-ajaxsubmit.js) to Submit Form to Pass Data to PHP File

Create a JS file with the name ‘jquery-ajaxsubmit.js’ to add the jQuery ajax code as given below. The below code uses the id of the form to submit it on button click without page refresh. Also, pass the url value as the PHP file (post.php) to pass the form data to the PHP file.

As the above <form> element contains the <div id="data"> element. The ajax code adds the result to this <div> element. The event.preventDefault(); is used to change the default behavior of the form and disable refresh of the page on form submission.

PHP Code (post.php) to Process Form Data

The last file is the PHP file where you have to add your PHP script to process your form data on submission. The below script collects the form data and display users entered details below the form.

It also checks whether the form fields are empty or not. If the form fields are empty, it displays the text to fill all form fields.

You May Also Like to Read

I hope you like this post on how to submit a form without page refresh using jQuery ajax submission and pass data to a PHP file.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.