How to submit this form using AJAX without jQuery but pure Javascript
formElem.onsubmit = async (e) =>
{
var url = document.getElementById("formElem").getAttribute("action");
e.preventDefault();
var data = new FormData(formElem);
data.append("submit", "Submit");
let response = await fetch(url,
{
method: 'POST',
body: data
});
let result = await response.json();
document.getElementById("field").value = "";
document.getElementById('charNum').innerHTML="0";
setTimeout(function autoscroll(){
var div = document.getElementById('loadmsg');
div.scrollTop = div.scrollHeight - div.clientHeight;
},1000);
};
Here is how you can submit your form via Ajax
:
function submitFormAjax() {
let xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200)
alert(this.responseText); // Here is the response
}
let name = document.getElementById('name').innerHTML;
let email = document.getElementById('email').innerHTML;
xmlhttp.open("GET","your_url.php?name=" + name + "&email=" + email, true);
xmlhttp.send();
}
This example is using GET
, but you could also use POST
:
xmlhttp.open("POST","your_url.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=" + name + "&email=" + email);
Note:
You must call submitFormAjax()
after validateFormOnSubmit
is done with no errors, here:
if (reason.length == 0) {
// Show some loading image and submit form
submitFormAjax();
} else {
return false;
}
In modern browsers, you can use fetch
in just a few lines:
fetch(form.action, {
method: form.method,
body: new URLSearchParams(new FormData(form)),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
I also published a slightly more complex version of this as an npm package, if you don't like copy-pasting code from StackOverflow: push-form