I\'m working with a form for which the mark-up I can\'t change & can\'t use jQuery. Currently the form post the results to a new window. Is it possible to change this to
A modern way using fetch would be:
const formData = new FormData(form);
fetch(form.action, {
method: 'POST',
body: formData
});
Note browser support and use this polyfil if IE-support is needed
function ajaxSubmit(form, callback) {
var xhr = new XMLHttpRequest();
var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
.filter(function(el) { return !!el.name; }) //Nameless elements die.
.filter(function(el) { return !el.disabled; }) //Disabled elements die.
.map(function(el) {
if (el.type=='checkbox') return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.checked);
else return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", form.action);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = callback.bind(xhr);
xhr.send(params);
};
Here's the simplest method I came up with. I haven't found an example that uses this exact approach. The code submits the form using a non-submit type button and places the results into a div, if the form is not valid (not all required fields filled), it will ignore the submit action and the browser itself will show which fields are not filled correctly.
This code only works on modern browsers supporting the "FormData" object.
<script>
function ajaxSubmitForm() {
const form = document.getElementById( "MyForm" );
if (form.reportValidity()) {
const FD = new FormData( form );
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("content_area").innerHTML = this.responseText; } };
xhttp.open("POST","https://example.com/whatever.php",true);
xhttp.send( FD );
}
}
</script>
<div id="content_area">
<form id="MyForm">
<input type="hidden" name="Token" Value="abcdefg">
<input type="text" name="UserName" Value="John Smith" required>
<input type="file" accept="image/jpeg" id="image_uploads" name="ImageUpload" required>
<button type="button" onclick="ajaxSubmitForm()">
</form>
</div>