Submit a Form Without Page Refresh Using jQuery

One of the best ways to improvise the user experience of the website is to validate and submit forms without refreshing the page.

In this tutorial, we’ll be showing the easiest method to validate and submit a contact form without page refresh using jQuery.

In the example, a simple contact form is taken consisting of a name, email, and phone number. The form submits all the fields to a PHP script without refreshing the page refresh with the use of native jQuery functions.

1) Build the HTML Form

Let’s see the HTML markup by creating a basic HTML form –

<div id="contact_form">
<form name="contact" action="">
  <fieldset>
    <div class="input-box">
    <label for="name" id="name_label">Name</label>
    <input type="text" name="name" id="name" minlength="3" placeholder="Monty" class="text-input" required/>
    </div>
     
    <div class="input-box">
    <label for="email" id="email_label">Email</label>
    <input type="email" name="email" id="email" placeholder="example@tutsplus.com" class="text-input"/>
    </div>
     
    <div class="input-box">
    <label for="phone" id="phone_label">Phone</label>
    <input type="tel" name="phone" id="phone" class="text-input" placeholder="856-261-9988"/>
    </div>
     
    <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
  </fieldset>
</form>
  <div class="greetings">
  <h1>Contact US</h1>
    <p>We are waiting to hear from you!</p>
  </div>
</div>

We have included a div with id contact_form that wraps around the entire form. Both the action and the method parts of the form tag blank. Make sure to include the id values for each input field.

We are also doing some very basic client-side validation using HTML5 attributes like required and minlength. The minlength attribute makes sure that users define a name that is at least three characters long.

Let’s add some CSS styles to create the following form –

* {
  box-sizing: border-box;
}
 
body {
  font-family: 'Roboto Slab';
  font-size: 1.5rem;
  font-weight: 300;
}
 
div#contact_form {
  width: 800px;
  display: flex;
  align-items: stretch;
  justify-content: space-evenly;
  border: 2px solid black;
  padding: 10px;
}
 
div.input-box {
  display: flex;
  margin: 10px 0;
  flex-wrap: wrap;
}
 
div.input-box label {
  display: inline-block;
  margin: 10px 10px 10px 0;
  width: 20%;
}
 
div.input-box input {
  font-size: 1.5rem;
  border: 1px solid #ccc;
  padding: 4px 8px;
  flex: 1;
}
 
input.button {
  font-size: 1.5rem;
  background: black;
  color: white;
  border: 1px solid black;
  margin: 10px;
  padding: 4px 40px;
}
 
h1 {
  font-size: 5rem;
  text-transform: uppercase;
  font-family: 'Passion One';
  font-weight: 400;
  letter-spacing: 2px;
  line-height: 0.8;
}
 
div.greetings {
  text-align: center;
  font-size: 1.2rem;
  background-color: #d3d3d3;
  background-image: linear-gradient(15deg, transparent 28%, rgba(255, 255, 255, 0.5) 28%);
  background-size: 50px;
}
 
div.input-box input.error {
    border: 2px dashed red;
    background: #fee;
}
 
div.input-box label.error {
    color: red;
    font-size: 1rem;
    text-align: right;
    width: 100%;
    margin: 10px 0;
}

Output

contact form using jquery without page load

2) Adding jQuery

Now, we’ll add some jQuery code. Let’s assume that you have downloaded jQuery, uploaded it to your server, and are referencing it in your webpage.

Open another new JavaScript file, mark it reference in your HTML as you would any normal JavaScript file, and add the following –

$(function() {
   // set up form validation here
});

This function will run when the HTML document is ready. Within this, we will set up the validation code.

3) Write Some Form Validation

Let’s write some basic form validation using jQuery. The use of a validation library offers us more control over the error messages that are displayed to users. It requires minimal or no changes in the markup of the form.

Start by loading the jQuery Validation library on the webpage. Add the following code –

$(function () {
  $("form").validate();
});

Pass the right selector while calling the validate() method. This validates the form without any need to write any error messages in the HTML or the logic to display and hide different error messages in JavaScript. Try to submit the form without filling in any values or adding incorrect input. The form showcases an error message like the below image.

Another benefit of the validation library it enables you to add conditional validation logic to your forms. Like you will be able to add code that needs a phone number only when the email address is not provided.

Output

4) Process Form Submission With the jQuery AJAX Function

Let’s start the process of submitting the form without a page refresh, that sends the form values to a PHP script in the background. Add the following code just below the validation snippet.

$( "form" ).on( "submit", function(e) {
 
    var dataString = $(this).serialize();
     
    // alert(dataString); return false;
 
    $.ajax({
      type: "POST",
      url: "bin/process.php",
      data: dataString,
      success: function () {
        $("#contact_form").html("<div id='message'></div>");
        $("#message")
          .html("<h2>Contact Form Submitted!</h2>")
          .append("<p>We will be in touch soon.</p>")
          .hide()
          .fadeIn(1500, function () {
            $("#message").append(
              "<img id='checkmark' src='images/check.png' />"
            );
          });
      }
    });
 
    e.preventDefault();
  });
});

Firstly, create a string of values, that are form values that will be passed along to the script that sends the email. This can be achieved by using the built-in serialize () method in jQuery. This way we don’t need to concatenate the values of different valid user inputs yourself.

We have commented out an alert to ensure that the right values are used in the process. If you uncomment that alert and then test your form, you will get a message as below.

Now, let’s start with the main AJAX function.

$("form").on("submit", function (e) {
    var dataString = $(this).serialize();
     
    $.ajax({
      type: "POST",
      url: "bin/process.php",
      data: dataString,
      success: function () {
        // Display message back to the user here
      }
    });
 
    e.preventDefault();
});

In the above code, The .ajax() function is used to process the values from our string called dataString with a PHP script known as bin/process.php, using the HTTP POST method type. If our script has been processed successfully, then display a message back to the user, and finally return false so the page does not reload.

Let’s summarize what happened in the example, to be sure we have covered everything. We have extracted the form values with jQuery using the serialize() method, and then placed those into a string like this:

var dataString = $(this).serialize();

Then, we used the jQuerys ajax() function to process the values in the dataString. Now, we have displayed a message back to the user and returns false so that the page does not refresh.

$.ajax({
      type: "POST",
      url: "bin/process.php",
      data: dataString,
      success: function() {
        $('#contact_form').html("<div id='message'></div>");
        $('#message').html("<h2>Contact Form Submitted!</h2>")
        .append("<p>We will be in touch soon.</p>")
        .hide()
        .fadeIn(1500, function() {
          $('#message').append("<img id='checkmark' src='images/check.png' />");
        });
      }
    });
    return false;

The success part of the script has been filled in with specified content that can be shown back to the user.

Output

submit contact form

5) Display a Message Back to the User

Firstly, change the entire contents of the #contact_form div with the following code –

$(‘#contact_form’).html(“<div id=’message’></div>”);

This replaces all the content within the contact form, using jQuery’s HTML() function. So instead of a form, we are having a new div with an id of the message. Fill that div with an actual message: an h2 saying Contact Form Submitted.

$(‘#message’).html(“<h2>Contact Form Submitted!</h2>”)

Add more content to the message with jQuery’s append() function, and effect by hiding the message div with the jQuery hide() function, and then fade it in with the fadeIn() function.

.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
  $('#message').append("<img id='checkmark' src='images/check.png' />");
});

After submitting the form, the user will see as below –

submit contact form

Conclusion

This is incredibly easy to submit forms without page refresh using jQuery’s powerful ajax() function. Retrieve the values in the JavaScript file, process them with the ajax() function, and return false. Process the values in the PHP script just like any other PHP file, the only difference being that the user does not have to wait for a page refresh.

For a contact form on your website, a login form, or even more advanced forms that process values through a database and retrieve the results, this can be done easily and efficiently with AJAX.