HOW TO SUBMIT AJAX FORMS WITH JQUERY

Introduction

jQuery can be paired with form submission lớn handle validation. This has the benefit of providing users with feedback on any errors in their input.

Bạn đang xem: How to submit ajax forms with jquery

*

In this tutorial, you will be presented with a sample form that communicates to a PHP backend. The khung will use jQuery lớn process a form without a page refresh (using AJAX), indicate any errors, & also display a success message.

Prerequisites

To complete this tutorial, you will need:

A code editor.A modern website browser.

Note: This tutorial does not specify the latest versions of jQuery (currently 3.5.1) or Bootstrap (currently 5.0.0-beta1). However, many of the lessons in this tutorial still pertain to lớn the latest versions.


This tutorial was verified with PHP v7.3.24, jQuery v2.0.3, and Bootstrap v3.0.3.

Step 1 — Building the Backend with PHP

For the purposes of this tutorial, the backend will be written in PHP.

First, xuất hiện a terminal window & create a new project directory:

mkdir jquery-form-validationNavigate to this new project directory:

cd jquery-form-validationThen, use your code editor to create a new process.php file:


$errors = <>;$data = <>;if (empty($_POST<"name">)) $errors<"name"> = "Name is required.";if (empty($_POST<"email">)) $errors<"email"> = "Email is required.";if (empty($_POST<"superheroAlias">)) $errors<"superheroAlias"> = "Superhero alias is required.";if (!empty($errors)) $data<"success"> = false; $data<"errors"> = $errors; else $data<"success"> = true; $data<"message"> = "Success!";echo json_encode($data);This file will take values for name, email, and superheroAlias. If any of these values are not provided, an error message will be sent back. Many other validations could be performed at this point, but for the purposes of this tutorial, you will only be ensuring these required inputs have been provided. Otherwise, if a value for name, email, và superheroAlias are present, a success message will be sent back.


Note: In a real-world scenario, the backend would also be responsible for other tasks such as taking the data và saving changes lớn a database, creating a session, or sending an email.


Now that you have the form processing completed, you can create the form.

Step 2 — Building the Frontend with HTML & CSS

For the purposes of this tutorial, Bootstrap will be used lớn build out the views.

In your project directory, use your code editor khổng lồ create an index.html file:


index.html

Open a terminal window & navigate to lớn the project directory. And run the PHP server:

php -S localhost:8000Visit localhost:8000 in your website browser & observe the following:

*

Now that you have the size completed, you can create the script khổng lồ handle size submission.

Step 3 — Handling form Submit súc tích in JavaScript and jQuery

To submit a khung via AJAX, your script will need to handle four tasks:

Capture the size submit button so that the default kích hoạt does not take place.Get all of the data from the khung using jQuery.Submit the form data using AJAX.Display errors if there are any.

In your project directory, use your code editor to create a new form.js file:


form.js

After saving your changes khổng lồ form.js, revisit the index.html file with your code editor. địa chỉ a reference lớn the new JavaScript file:


index.html

Note: You will be using the .done callback khổng lồ handle a successful AJAX request. This used to lớn be called .success, but that has since been deprecated in jQuery 1.8+.

Another alternative is lớn use serialize instead of pulling the form information individually.

Xem thêm: Kiếm Tiền Với Accesstrade Là Gì, Accesstrade Là Gì


The PHP script will process the inputs that the AJAX gọi sent & return the $data<> array that was created. You can observe this in your browser’s console after you submit your form:

*

Now that you have the form logic completed, you can create the script to handle size errors.

Step 4 — Displaying khung Validation Errors

In the PHP script, the code checks to ensure that all the fields are required. If a field is not present, an error is sent back.

Revisit form.js and địa chỉ the following highlighted lines of code:


form.js

// ... $.ajax( type: "POST", url: "process.php", data: formData, dataType: "json", encode: true, ).done(function (data) console.log(data); if (!data.success) if (data.errors.name) $("#name-group").addClass("has-error"); $("#name-group").append( "
" + data.errors.name + "
" ); if (data.errors.email) $("#email-group").addClass("has-error"); $("#email-group").append( "
" + data.errors.email + "
" ); if (data.errors.superheroAlias) $("#superhero-group").addClass("has-error"); $("#superhero-group").append( "
" + data.errors.superheroAlias + "
" ); else $("form").html( "
" + data.message + "
" ); ); event.preventDefault(); });// ...This code checks khổng lồ see if the response contains an error for each field. If an error is present, it adds a has-error class và appends the error message.

Now, revisit your size in a website browser and experiment with submitting data with the form.

If there are any errors that come back from the server, the khung will provide feedback on any required fields:

*

And if there are no errors that come back from the server, the form will provide feedback for a successful submission:

*

Every time we submit the form, our errors from our previous submission are still there. You will need khổng lồ clear them by removing them as soon as the size is submitted again.

Revisit form.js and địa chỉ the following highlighted lines of code:


form.js

// ... $("form").submit(function (event) $(".form-group").removeClass("has-error"); $(".help-block").remove(); // ... );// ...This code will remove the has-error class from all .form-group elements. It will also remove all .help-block elements with error messages.

Step 5 — Displaying server Connection Errors

If there is an error connecting lớn the server, there will be no JSON response from the AJAX call. Lớn prevent users from waiting for a response that will never arrive, you can provide an error message for connection failures.

Revisit form.js and địa chỉ cửa hàng the following highlighted lines of code:


form.js

// ... $.ajax( type: "POST", url: "process.php", data: formData, dataType: "json", encode: true, ) .done(function(data) // ... ) .fail(function (data) $("form").html( "
Could not reach server, please try again later.
" ); );// ...If the vps is broken or down for any reason, a user who attempts khổng lồ submit a form will get an error message:

*

Now that you have the vps error message complete, you have completed the example form.

Using $.post instead of $.ajax

jQuery also provides a $.post shorthand method as an alternative to lớn $.ajax.

The $.ajax code in form.js could be rewritten with $.post:

$.post("process.php", function(formData) // place success code here) .fail(function(data) // place error code here );The advantage of $.post is it does not require as much connection configuration to be declared.

Conclusion

In this article, you built a sample size that communicates khổng lồ a PHP backend with jQuery và displays any errors in the form.

As a next step, you will want to explore more complex validations lượt thích valid email addresses and dates. You may also be interested in applying client-side validations that work in the browser.

If you’d like to learn more about JavaScript, kiểm tra out our JavaScript topic page for exercises & programming projects.