How To Submit This Form Using Ajax Without Jquery But Pure Javascript
I looked all over and all I could find was about jQuery. With much help from the great minds here at SO I've finally got my form validating (it's only client side right now, but th
Solution 1:
Here is how you can submit your form via Ajax
:
functionsubmitFormAjax() {
let xmlhttp= window.XMLHttpRequest ?
newXMLHttpRequest() : newActiveXObject("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 {
returnfalse;
}
Solution 2:
In modern browsers, you can use fetch
in just a few lines:
fetch(form.action, {
method: form.method,
body: newURLSearchParams(newFormData(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
Solution 3:
formElem.onsubmit = async (e) =>
{
var url = document.getElementById("formElem").getAttribute("action");
e.preventDefault();
var data = newFormData(formElem);
data.append("submit", "Submit");
let response = awaitfetch(url,
{
method: 'POST',
body: data
});
let result = await response.json();
document.getElementById("field").value = "";
document.getElementById('charNum').innerHTML="0";
setTimeout(functionautoscroll(){
var div = document.getElementById('loadmsg');
div.scrollTop = div.scrollHeight - div.clientHeight;
},1000);
};
Post a Comment for "How To Submit This Form Using Ajax Without Jquery But Pure Javascript"