Home >Backend Development >PHP Tutorial >How to submit a form using native XMLHttpRequest object?
HTML:
<code><form id="info"> <label for="id">ID: </label> <input type="text" name="id"> <br> <label for="user">User: </label> <input type="text" name="user" id="user"> <br> <input type="submit" name="submit" id="submit"> </form></code>
JavaScript:
<code>var submit = document.getElementById("submit"); submit.onclick = function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.state == 4) { if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { console.log(xhr.responseText); } else { alert("HttpRequest was unsccessful: " + xhr.status); } } } xhr.open("post", "form.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("info"); xhr.send(serialize(form)); }</code>
form.php
<code><?php $id = $_POST['id']; $user = $_POST['user']; echo $id . $user; ?></code>
The code is as above. The effect I want to achieve is the same as adding action and method attributes to the form. After submission, it can automatically jump to form.pp.
But there is no response when submitting like this. After searching, it is all about jquery. Still don’t know the format of submitting a form using ajax.
HTML:
<code><form id="info"> <label for="id">ID: </label> <input type="text" name="id"> <br> <label for="user">User: </label> <input type="text" name="user" id="user"> <br> <input type="submit" name="submit" id="submit"> </form></code>
JavaScript:
<code>var submit = document.getElementById("submit"); submit.onclick = function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.state == 4) { if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { console.log(xhr.responseText); } else { alert("HttpRequest was unsccessful: " + xhr.status); } } } xhr.open("post", "form.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("info"); xhr.send(serialize(form)); }</code>
form.php
<code><?php $id = $_POST['id']; $user = $_POST['user']; echo $id . $user; ?></code>
The code is as above. The effect I want to achieve is the same as adding action and method attributes to the form. After submission, it can automatically jump to form.pp.
But there is no response when submitting like this. After searching, it is all about jquery. Still don’t know the format of submitting a form using ajax.
Try changing xhr.send(serialize(form))
to
<code>var formData = new FormData(form); xhr.send(formData);</code>
formData is HTML5 used to submit forms asynchronously, which should be able to meet the needs of the original poster.
Reference http://www.cnblogs.com/lhb25/...
<code>var fd = new FormData; fd.append("username",document.querySelector("#username").value); fd.append("password",document.querySelector("#password").value); ... xhr.send(fd);</code>