Most of the time you need to submit the form asynchronously, when the form is too much is time, one getElementById becomes very impractical
Of course, jquery can implement the asynchronous submit form, jquery.form.js This library seems to be very popular
Just sometimes do not want to use the extra library, so think of their own writing, with pure JS to implement asynchronous submission form
Implemented as follows (this example is submitted by post, using PHP as a server script)
HTM L File: Test
JS file: Name_form.js
function createxmlhttp () {var xmlHttp = null;
try {//firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest ();
catch (E) {//ie try {xmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} return xmlHttp;
function SubmitForm (formid) {var xmlHttp = createxmlhttp (); if (!xmlhttp) {alert ("Your browser does not support ajax!
");
return 0;
The var url = ' test.php ';
var postdata = "";
PostData = "Username=" + document.getElementById (' username '). value;
PostData + + "t=" + math.random ();
Xmlhttp.open ("POST", url, True);
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate = = 4 && Xmlhttp.status =) {if (XMLH
Ttp.responsetext = = ' 1 ') {alert (' post successed ');
}} xmlhttp.send (PostData); }
PHP File: test.php
<?php
if (isset ($_post[' username ')) {
echo ' 1 ';
}
? >
The principle of the above program is that the user first used to enter the username information in the test.html file, and then through the name_ Form.js file to implement the AJAX implementation of the form, and then in the PHP file to operate, here just to determine whether the user name is set, that is, whether the user name exists, the existence of the output of 1, in addition, the database can also operate (add, change, etc.), and then judge the operation results, if the result is true then output 1, in the JS file in the XML Http.responsetext to judge the returned information, because only output 1, so the correct judgment, at this point pop-up prompt box, the content is ' post successed '. This is the successful implementation of the AJAX implementation of PHP asynchronous submission form.
Note: To ensure that the PHP file echo does not have any output before, so Ajax can accurately get the information returned.
Above this pure JavaScript AJAX implementation of PHP asynchronous submission Form Simple example is a small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.