Submit the form without refreshing the page using jQuery.

One of the best ways to improve your website’s user experience is to validate and submit forms without page refresh.

In this tutorial, I will show you how easy it is to do – validate and submit the contact form without refreshing the page using jQuery! Let’s begin.

What are we making

In this example, we have a simple contact form with name, email and phone number. The form submits all fields in PHP script without any page updates, using local jQuery functions.

1. Create HTML forms

Let’s take a look at our HTML markup. We start with our basic HTML form:

You may notice that I have added one div With ID contact_form Which wraps around the whole shape.

Make sure you don’t miss out. div In your own form as we will need this wrapper. div later on. You may also notice that I have left blank both the action and method parts of the form tag. We don’t really need any of them here, because jQuery takes care of it later.

Another important thing is to make sure to include. id Values ​​for each input field. Of id Values ​​are what your jQuery script will look for to process the form.

We’re also doing some very basic client-side validation using HTML5 attributes. required And minlength. Of minlength The attribute will ensure that the user provides a name that is at least three characters long. Similarly, d required Attribution ensures that users fill in all the required form values.

You can read more about these attributes in our tutorial on verifying form input using HTML5 and Regex only.

  • HTML5
    Form input validation using HTML5 and Regex only
    Monty Shocken

I’ve included some CSS styles for developing the following forms:

Contact formContact formContact form

2. Start adding jQuery.

The next step in this process is to add some jQuery code. I’m going to assume that you downloaded jQuery, uploaded it to your server, and referenced it in your web page.

Next, open another new JavaScript file, refer to it in your HTML as you would any normal JavaScript file, and add the following:

This function works as soon as the HTML document is ready. This function is similar to the jQuery document.ready function if you have previously done something in jQuery. Inside, we’ll set up our verification code.

3. Write some form confirmation.

We will now write some basic form validation using jQuery. This will improve our validation so far. Using the authentication library gives us more control over the error messages displayed to users. This requires minimal or no change in the markup of the form.

Get started by loading the jQuery authentication library on your webpage. Now, just add the following code:

Make sure you pass the correct selector when making the call. validate() This method will validate the form without having to write error messages in HTML or logic to show and hide various error messages in JavaScript. Try to submit the form without filling in any value or intentionally entering incorrect input. The form will show a nice error message like the picture below.

Form verification error messageForm verification error messageForm verification error message

Using the authentication library also allows you to add conditional authentication logic to your forms. For example, you’ll be able to add a code that requires a phone number only if an email address isn’t provided. I have covered this in more detail in the jQuery Form Verification Tutorial.

  • Javascript
    Easy form validation with jQuery
    Monty Shocken

4. Follow the form submission with jQuery AJAX function.

Now, we come to the part where we talk about the middle ground – tutorials – submitting your form without refreshing the page, which sends the form values ​​to the PHP script in the background. Let’s first take a look at all the code, and then I’ll break it down into more detail. Include the following code that we added earlier at the very bottom of the verification pieces:

A lot is happening here! Let’s break it all down – once you understand the process it’s very simple and very easy to use.

We first create a string of values, which are all form values ​​that we want to pass on to the script that sends the email. This built-in can be easily obtained using them. serialize() Method in jQuery. That way, you don’t have to worry about finding and integrating different valid user input values ​​yourself.

I’ve commented on a warning that I sometimes use to make sure I’m catching the right values, which can help you along the way. If you disregard this alert and check your form, assuming that everything is OK so far, you should receive the following message:

Data string alertData string alertData string alert

Now we come to our main AJAX function, which is the star of today’s show. This is where all the action takes place, so pay close attention!

Basically, what is happening in the code is: The .ajax() The function processes the values ​​of our string. dataString With a PHP script called Become / act.php, Using HTTP POST method type. If our script is successfully executed, we may return a message to the user, and finally return false So the page does not reload. that’s it! In these few lines the whole process is handled right there!

In addition to giving a message of success, you can do more innovative things here. For example, you can send your values ​​to a database, process them, and then return the results to the user. So if you’ve posted a poll for users, you can process their vote, and then return the voting results, all without the need for a page refresh.

Let’s summarize what happened in our example, to make sure we covered everything. We retrieved our form values ​​using jQuery. serialize() Method, and then placed them in a string like this:

Then we used jQuery. ajax() Function to process values ​​in dataString. After this process is successfully completed, we return a message to the user and return false So that our page is not refreshed:

The successful part of the script is filled with certain content that can be shown back to the user. But as far as our AJAX functionality is concerned, that’s all. For more options and settings, be sure to check out the jQuery documentation ajax The function here is one of the easiest to implement, but nonetheless, it is very powerful, as you can see.

5. Show the message back to the user.

Let’s take a brief look at this part of the code that returns our message to the user to finish the tutorial.

First, we change the entire content #contact_form div (Remember I said we would need it. div) With the following line:

It replaces all the content inside the contact form, using jQuery. html() Function So instead of a form, we now have a new one. div With one id Of message. Next, we fill this div with a real message: a h2 Is saying Contact form submitted:

We will add more content to the message with jQuery. append() To eliminate the function, and everything, we have a cool effect by hiding the message div with jQuery. hide() Function, and then finish with it. fadeIn() Function:

So the user after submitting the form sees the following:

Successful submissionSuccessful submissionSuccessful submission

Result

So far, I think you have to agree that it is incredibly easy to submit a form without refreshing the page using the powerful jQuery. ajax() Function Just get the values ​​in your javascript file, follow them. ajax() Function, and return false. You can process the values ​​in your PHP script just like you would on any other PHP file, the only difference being that the user does not have to wait for the page to refresh – it all happens quietly in the background. ۔

So if you have contact forms, login forms, or even more sophisticated forms on your website that process values ​​and retrieve results via a database, you can easily do this with AJAX and Can effectively

Learn JavaScript with a free course.

If you want to master JavaScript, be sure to check out our free course to learn the basics of modern JavaScript.

In this course, you will learn all the essential concepts of JavaScript language. That’s right: that’s all! Including the most important recent language improvements in JavaScript ES6 (ECMAScript 2015) and JavaScript ES7 (ECMAScript 2016).

You will start with the basic principles of language: variables and data types. Then in each lesson you will generate knowledge from data structures such as rows and maps to loops, control structures and functions. Along with the basics of the language, you’ll also learn some built-in APIs for working with data, AJAX, and web browser DOMs. Finally, you will take a look at the most powerful and widely used web APIs that are supported by all modern browsers.

  • Free

    Javascript
    Basic Principles of Modern JavaScript
    Dan Wilman

Write a Comment

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