It’s the era of single page applications. AJAX is the pillar behind all such great user experience. Nobody likes that old same page loading stuff on every request. You can massively improve your user experience by implementing AJAX. It creates an amazing native feel. In this post, we will learn to use jQuery AJAX form submit with an example.

jQuery

jQuery is one of the most popular JavaScript libraries. It’s quite old and does not provide a lot of features as compared to today’s libraries. However, people still prefer to use it because of its light-weight, huge community, smaller learning curve.

AJAX (Asynchronous JavaScript and XML)

In simple words, AJAX is a process by which we can get or post data without refreshing the page. It is not that much beginner friendly. However, jQuery made AJAX look really simple.

jQuery AJAX form submit

We will create a simple application to learn jQuery AJAX form submit with example.

Generally, there will be two pages. One to display the form another to get the form data and manipulate.

First of all, we will simplify the steps with the following steps.

  • Create a Index.php file and a form.php file
  • Write the code to display the form in index file
  • Write the code to manipulate the submitted data in form file
  • Add AJAX code to index file to send form data to form file

Above we have just written the steps to achieve the AJAX forms. Now we will see jQuery AJAX form submit with example.

The front end part

In this part we will write code to create the form. We will use Bootstrap to make things look beautiful.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <title>jQuery AJAX form submit</title>
</head>
<body>
  <div class="container mt-3">
    <div class="row justify-content">
      <div class="col-md-8">
        <h2>jQuery AJAX form submit</h2>
        <form action="form.php" method="POST">
          <div class="form-group">
            <input type="text" name="name" id="name" class="form-control" placeholder="Name">
          </div>

          <div class="form-group">
          <input type="email" name="email" id="email" class="form-control" placeholder="Email">
          </div>

          <button class="btn btn-primary" type="submit">Submit</button>
        </form>
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>

jquery ajax form submit with bootstrap

In the above code there is a simple HTML markup to create a form. This above form has two fields name and email. The form has method post and action form.php. Until yet there is no AJAX included in our project. So on submit the page will redirect to the specified URL in action attribute.

Now let’s move to the back end part and create the form.php file.

The back end part

That is the main part where we will send data with AJAX and get the response. You can manipulate data the way you want here.

However, it is a small tutorial so we will just create an empty array and populate the array with data from the form. Once we get our data we will encode it to JSON and send back as reponse to the AJAX.

<?php
	$form_data = array();

	$form_data['name'] = $_POST['name'];
	$form_data['email'] = $_POST['email'];

	echo json_encode($form_data);
?>

Now our application is ready, run it and check the output. You will see it’s echoing out the data successfully. So let’s move to the final step and add the AJAX part.

jQuery AJAX form submit with example – the AJAX part

jquey ajax form submit with php

So let’s go step by step again and make things look easier. Okay! so let’s create the form submit event first and serialize the form data.

<script>
  $(document).ready(function() {
    $('form').submit(function(e) {
      e.preventDefault();
      var values = $(this).serialize();
    })
  });
</script>

The above code will execute as soon as the page loads entirely. Once it’s loaded totally the form will not submit by default.

Look at the event closely, we have used the preventDefault to stop it from submitting like default. We will use AJAX so we must stop it’s default behaviour.

On the next line we have created a variable called values to store the form data. The serialize method serializes the data. In order to send data with AJAX serialization is required.

The term serialize means a text string in URL-encoded notation.

Example – name=Subham&[email protected]

The AJAX method

Finally, it is the time to add the ajax method.

$.ajax({
  url: "form.php",
  type: "post",
  data: values ,
  success: function (res) {
    alert('Form submitted successfully...')
    console.log(res)
  },
  error: function(xhr, status, error) {
    console.log(xhr.responseText);
  }
});

The above code is really neat and clean to understand just by going through the lines. At the beginning we have specified the url or the form action attribute. Later that we have defined the type of request.

** We have mentioned the url and type property with the form markdown also. So you can scrape it from there also.

Now thereafter data must set to our values string. So that’s the main key points of the AJAX call.

So you can send data in this way. Now in order to display a success or error message we must write the methods for success and error. If the form successfully submits the form data we will show an alert and show the res or response within the console.

In case of error we will directly show the error text within console.

So that’s it guys. Hope you’ve liked the post. In this post you have learned to create jQuery AJAX form submit with PHP.

Let us know if we have missed something in the comment section below.


Subham Mitra

Subham Mitra is a full-stack developer as well as well as an aspiring entrepreneur who is pursuing MCA and providing brilliant stuff for a great range of people's through Coders Diaries.

https://codersdiaries.com


Leave a Reply

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.

WhatsApp WhatsApp us