JQuery creates an example of php ajax form submission _ jquery

Source: Internet
Author: User
Tags contact form
In this example, only functions and functions of the JQuery class library are used, and third-party plug-ins are not required. In addition, all form information is sent to the Administrator using the PHPMailer class library email. If you are not familiar with JQuery's basic syntax, search for the tutorial resources on this site. If you are not familiar with PHPMailer usage, please refer to another article on this site, "Use PHPMailer class library to send emails".

Step 1: create a form HTML page

Here, we only show the HTML Structure Code of the main form part:

The Code is as follows:






Notes:

Here, a contact_form id is used to include the entire contained information. This is meaningful and will be used later when JavaScript interacts with users.
It should be noted that the attributes of the form tag include both method and action. In fact, this is of little significance. Because Javascript directly operates the DOM, it is also possible not to have these two attributes;
Required to input The label is added with an independent id, which is similar to the second principle. Otherwise, you cannot see the normal effect.




Step 2: add the JQuery code

Assume that you have downloaded the JQuery base library from the official JQuery website, uploaded it to your WEB server, and added it to the WEB page you want to use.

Create another JS file and add the following code:

The Code is as follows:


$ (Function (){
$ (". Button"). click (function (){
// Process form verification and the logic handed over to the background for processing
});
});


The function () in the first line is used and used in the same way as the document. ready function in Jquery. It is automatically triggered after DOM preparation.
The second row contains a click trigger function click (). Note that a Class named "button" needs to be placed on the HTML page submit button, to simulate the submi form submission function.
From the second point, we can see that JQuery can well separate the structure and logic.
Step 3: Write Verification Code

In practice, this step is essential. Prompt when you enter a project by mistake.

The Code is as follows:



$ (Function (){
$ ('. Error'). hide ();
$ (". Button"). click (function (){
// Verify the 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;
}

});
});


Notes:
In row 2nd, we add a $ ('. error'). hide () label to hide the label labels with three class = "error" prompts when the user does not enter any information. The error only appears when an error occurs, that is, it is null. (Because it has the function of return false, only one error occurs at a time)
In JQuery, it is very easy to get the value of an ID or Class in the DOM.

The Code is as follows:


// Obtain the id value
Var name = $ ("input # name"). val ();
// Obtain the value of class number 1
Var name = $ (". name") [1]. val ();
Assuming that the user has not entered a name, the processing logic should be: first display the error, and then focus on the name.


If (name = "") {// the user name is blank
$ ("Label # name_error"). show (); // error message
$ ("Input # name"). focus (); // focus location
Return false; // return
}


When verifying a required field, return false is required. Otherwise, the required field is submitted.
Step 4: submit the form information using Jquery's Ajax function.

This is the core step for implementing the process of refreshing the new commit. The ajax function is used to submit the form item value obtained by javascript from the DOM and then asynchronously submitted to the background handler (process. php), and send an Email. This step is followed by the verification program:

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 (){
Certificate ('{contact_form'}.html ("

");
Certificate ('{message'{.html ("contact information submitted successfully! ")
. Append ("

Script by Code52.net

")
. Hide ()
. FadeIn (1500, function (){
$ ('# Message'). append ("");
});
}
});
Return false;


The core function of the above code is. ajax () is used to asynchronously transmit the obtained form information (dataString) to the defined backend PHP url (bin/process. php ). If the data is successfully transmitted, it will return a series of defined information to the user. Finally, return false to prevent page reloading.
In addition to returning successful messages and sending emails, we can also do more extensive things. For example, when the obtained data is processed by a background script, the data is inserted into the database and the information submitted by the user is returned.
Explanation:

First, obtain the value of the form item. The method is mentioned in step 3:
Var name = $ ("input # name"). val ();
Var email = $ ("input # email"). val ();
Var phone = $ ("input # phone"). val ();
// Combine the values of form items into a string
Var dataString = 'name = '+ name +' & email = '+ email +' & phone = '+ phone;
Pass the value of this character string to the background url through the AJAX function. If the value is successful, a success message is returned to the user:

The Code is as follows:


$. Ajax ({
Type: "POST ",
Url: "bin/process. php ",
Data: dataString,
Success: function (){
Certificate ('{contact_form'}.html ("

");
Certificate ('{message'{.html ("Contact Form Submitted! ")
. Append ("

We will be in touch soon.

")
. Hide ()
. FadeIn (1500, function (){
$ ('# Message'). append ("");
});
}
});
Return false;


In this example, ajax functions only have these functions. For more information about ajax functions, see the official documentation: jQuery's documentation on the ajax function.
Step 5: feedback to users

First, after the information is submitted successfully, JQuery will dynamically replace it with the following parts:

The content in, you only need a simple sentence to achieve.
Certificate ('{contact_form'}.html ("

");
For example, if you use the dynamic criptmode to replace a layer, you can use the jquery.html method, which is very simple and convenient.
Secondly, it is not enough to have this layer, because there is no content in it, so we also need to add some display content to this layer of id = message:
Certificate ('{message'{.html ("contact information submitted successfully! ")
Similarly, a piece of html is added to the dynamic message layer for the prompt. You can also use the append method to append a sentence to the message layer:
. Append ("

We will be in touch soon.

")
Finally, we set the following special effect code to demonstrate the dynamic effect of server processing after submission:
. Hide () // The entire layer disappears
. FadeIn (1500, function () {// gradually appears within 1500 milliseconds
// Append a successful icon dynamically.
$ ('# Message'). append ("");
});

Note: If you want to use this instance in practice, you may need to make some modifications. For example, add verification information rules and set a Loading icon when the user submits information. This tutorial is only for reference. In addition, please note that I will not explain it here when submitting data to the mailbox in the background. The downloaded package contains detailed comments. You only need to change the username and password. After downloading the compressed package, you may find that there is a runonload. js file, which is used to focus on the input form when loading the Form file.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.