Table of Contents
Contact information submitted successfully!
Contact Form Submitted !
Contact information has been submitted successfully!
Home Web Front-end JS Tutorial JQuery creates PHP AJAX form submission example_jquery

JQuery creates PHP AJAX form submission example_jquery

May 14, 2018 pm 03:15 PM
ajax jquery form submission

If you are not familiar with the basic syntax of JQuery, please search the tutorial resources on this site. If you are not familiar with the usage of PHPMailer, please check out another article on this site "Using the PHPMailer Class Library to Send Emails".
The first step is to create a form HTML page
Here, we only show the main form part of the HTML structure code:

The code is as follows:

<div id="contact_form"> 
<form name="contact" method="post" action=""> 
<fieldset> 
<label for="name" id="name_label">姓名</label> 
<input type="text" name="name" id="name" size="30" value="" class="text-input" /> 
<label class="error" for="name" id="name_error">此项必填</label> 
<label for="email" id="email_label">您的Email</label> 
<input type="text" name="email" id="email" size="30" value="" class="text-input" /> 
<label class="error" for="email" id="email_error">此项必填</label> 
<label for="phone" id="phone_label">您的联系电话</label> 
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" /> 
<label class="error" for="phone" id="phone_error">此项必填</label> 
<br /> 
<input type="submit" name="submit" class="button" id="submit_btn" value="我要发送" /> 
</fieldset> 
</form> 
</div>
Copy after login

A few Note:
Here, a contact_form with id is used to contain the entire included information; this is meaningful and will be used later when JavaScript interacts with the user.
Everyone should have noticed that the attributes of the form tag here include both method and action; this does not mean much, because Javascript directly operates the DOM, so it is okay without these two attributes;
Be sure to give the user The input tag is added with an independent ID, which is similar to the second principle. Otherwise, normal effects cannot be seen.
The second step is to start adding JQuery code
It is assumed that you have downloaded the JQuery base library from the JQuery official website, then uploaded it to your WEB server, and added it to the web page you want to use.
Now create a new JS file and add the following code:

Copy the code The code is as follows:

$(function( ) {
$(".button").click(function() {
// Handle the logic of form validation and background processing
});
});

The function() function in the first line has the same usage and function as Jquery’s document.ready function, and is automatically triggered after the DOM is prepared.
The second line contains a click trigger function click(). It should be noted that a Class named "button" needs to be placed on the HTML page submission button to simulate the function of submitting the form.
From the second point we can see that JQuery can separate structure and logic very well.
The third step is to write the verification code
In practical applications, this step is essential. When the user misses or fills in an item incorrectly, prompt them promptly.

Copy code The code is as follows:

$(function() {
$('.error').hide ();
$(".button").click(function() {
// Verification code

$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input# name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $(" input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone"). focus();
return false;
}
});
});

A few notes:
In line 2, we add a $('. error').hide() is to hide three label labels with class="error" that prompt errors when the user does not enter any information. And the error will only appear if there is an error, i.e. it is empty. (Because of the function of return false, only one error will occur each time)
In JQuery, it is very simple to obtain the value of an ID or Class in the DOM

Copy the code The code is as follows:

//Get the value of id
var name = $("input#name").val();
//Get the class number A value of 1
var name = $(".name")[1].val();
Now assuming that the user does not enter a name, the processing logic should be: first display the error, and then position the focus on the name superior.
if (name == "") { //The user name is empty
$("label#name_error").show(); //Error message
$("input#name"). focus(); //Focus positioning
return false; //Return
}

When validating the required fields, you must return false, otherwise the required fields will be incomplete. That is the case of submission.
The fourth step is to submit the form information through Jquery’s Ajax function.
This is the core step in this tutorial to implement refresh-free submission. The form item value obtained by JavaScript from the DOM is submitted through the ajax function, and then submitted asynchronously to the background processing program (process.php), and an email is sent. This step is immediately after the verification process:

Copy code The code is as follows:

var dataString = 'name=' name ' &email=' email '&phone=' phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process. php",
data: dataString,
success: function() {
$('#contact_form').html("

");
$('#message ').html("

Contact information submitted successfully!

")
.append("

Script by Code52.net

")
.hide()
.fadeIn(1500, function () {
$('#message').append("JQuery creates PHP AJAX form submission example_jquery");
});
}
});
return false;
The above code The core function is .ajax(). Its function is to use the POST method to asynchronously transmit the obtained form information (dataString) to the defined background PHP url (bin/process.php). If the data is successfully transmitted, it A series of messages that we define will be returned to the user, and finally return false. This is to prevent the page from reloading.
In addition to returning success messages and sending emails, we can also do other more extensive things, such as. When the obtained data is processed by the background script, the data is inserted into the database, and then the information submitted by the user is returned.
Detailed explanation:
First, get the value of the form item. We have already done this in the third step. Mentioned in:
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
//Combine the values ​​of the form items into a string
var dataString = 'name=' name '&email=' email '&phone=' phone;
The value of this combined string is passed to the background url through the AJAX function. If successful, success information will be returned to the user:

Copy code The code is as follows:

$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("

");
$('#message').html("

Contact Form Submitted !

")
.append("

We will be in touch soon.

")
.hide()
.fadeIn( 1500, function() {
$('#message').append("JQuery creates PHP AJAX form submission example_jquery");
});
}
});
return false;
In this example, this is the only function of the ajax function. If you need further information about the ajax function, you can refer to the official documentation: jQuery's documentation on the ajax function
Step 5, feedback information to the user
First of all, after the information is submitted successfully, JQuery will dynamically replace the content in

through the following part, which can be achieved with just a simple sentence.
$('#contact_form').html("

");
So please remember, if you need to dynamically replace a certain layer through JavaScript in the future, you can use Jquery .html method implementation, very simple and convenient.
Secondly, having this layer is definitely not enough, because there is no content in it, so we also need to add some display content to the layer with id=message:
$('#message').html("

Contact information has been submitted successfully!

")
A piece of html is also dynamically added for the layer with the id of message. You can also use the append method to add a sentence in the message layer:
.append("

We will be in touch soon.

")
Finally, in order to show that after submission , the dynamic effect of server processing, we set the following special effects code:
.hide() //The entire layer disappears
.fadeIn(1500, function() {//Gradually appears within 1500 milliseconds
/ /Finally, dynamically append a success icon
$('#message').append("JQuery creates PHP AJAX form submission example_jquery");
});
Postscript: If you want to apply this example in practice, maybe Some changes still need to be made. For example, add verification information rules, set a Loading icon during the user's submission of information, etc. This tutorial is only used to introduce ideas. In addition, please note that data is submitted to the mailbox in the background, which I will not explain here. There are very detailed comments in the packaged download examples. All you need to change is the username and password. After downloading the compressed package, you may find that there is a runonload.js file inside. The function of this file is to focus on the input form when loading the form file, and that's it.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to implement front-end and back-end interaction in layui How to implement front-end and back-end interaction in layui Apr 01, 2024 pm 11:33 PM

There are the following methods for front-end and back-end interaction using layui: $.ajax method: Simplify asynchronous HTTP requests. Custom request object: allows sending custom requests. Form control: handles form submission and data validation. Upload control: easily implement file upload.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

What is the role of Serverlet in Java What is the role of Serverlet in Java Apr 12, 2024 pm 02:39 PM

Servlet serves as a bridge for client-server communication in Java Web applications and is responsible for: processing client requests; generating HTTP responses; dynamically generating Web content; responding to customer interactions; managing HTTP session state; and providing security protection.

The difference between event and $event in vue The difference between event and $event in vue May 08, 2024 pm 04:42 PM

In Vue.js, event is a native JavaScript event triggered by the browser, while $event is a Vue-specific abstract event object used in Vue components. It is generally more convenient to use $event because it is formatted and enhanced to support data binding. Use event when you need to access specific functionality of the native event object.

How to build a single-page application using PHP How to build a single-page application using PHP May 04, 2024 pm 06:21 PM

Steps to build a single-page application (SPA) using PHP: Create a PHP file and load Vue.js. Define a Vue instance and create an HTML interface containing text input and output text. Create a JavaScript framework file containing Vue components. Include JavaScript framework files into PHP files.

What is the abbreviation of dom in js? What is the abbreviation of dom in js? May 09, 2024 am 12:00 AM

DOM (Document Object Model) is an API for accessing, manipulating and modifying the tree structure of HTML/XML documents. It represents the document as a node hierarchy, including Document, Element, Text and Attribute nodes, which can be used to: access and modify Document structure Access and modify element styles Create/modify HTML content in response to user interaction

See all articles