Simple Example of php asynchronous form submission using javascript ajax, javascriptajax
Many times forms need to be submitted asynchronously. When there are too many forms, one getElementById becomes impractical.
Of course, jquery can implement asynchronous form submission. jquery. form. js library seems quite popular.
But sometimes I don't want to use additional libraries, so I try to write it myself and use pure js to Implement Asynchronous form submission.
Implementation is as follows (this example uses the POST method and php as the 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;} 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 = 200) {if (xmlHttp. responseText = '1') {alert ('Post successed ') ;}} xmlHttp. send (postData );}
Php file: test. php
<?php if(isset($_POST['username']) { echo '1'; }?>
The statement is as follows: first, the user enters the username information in the test.html file, then submits the form through ajax in the name_form.js file, and then operates in the PHP file. Here, the user name is determined to be set, that is, whether the user name exists, if yes, output 1. In addition, you can perform operations (ADD, modify, etc.) on the database and then determine the operation result. If the result is true, output 1, xmlHttp In the js file. responseText determines the returned information. Because only 1 is output, the result is correct. A prompt box is displayed, with the content 'Post successed '. In this way, php asynchronous form submission is implemented using ajax.
Note: ensure that the PHP file echo does not have any output before, so that ajax can accurately obtain the returned information.
The simple example of the above pure javascript ajax Implementation of php asynchronous form submission is all the content shared by xiaobian. I hope to give you a reference, and I hope you can also support the help house.