JQuery creates PHP AJAX form submission example_jquery
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>
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("");
});
}
});
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("");
});
}
});
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("");
});
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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools