Home > Web Front-end > JS Tutorial > body text

JQuery creates PHP AJAX form submission example_jquery

ringa_lee
Release: 2018-05-14 15:15:54
Original
1743 people have browsed it

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.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template