I would like to send some data (via javascript) to a server-side PHP script which then uses the data it has been sent to return a new piece of data to the client-side javascript.
The new piece of data is otherwise inaccessible to the javascript because it's contained in a PHP associative array in an external file. Only the PHP script can retrieve the new data from that external file.
I'm guessing this should be straightforward using Ajax, but I am doing something wrong.
My alternative approach to Ajax (which is working) is to build a form dynamically which sends the data to the PHP script:
Approach using Dynamically Built Form
var makeshiftAjaxReplacement = document.createElement('form');
makeshiftAjaxReplacement.setAttribute('method', 'post');
makeshiftAjaxReplacement.setAttribute('action', '/server-side-script.php');
var data1Input = document.createElement('input');
data1Input.setAttribute('type', 'hidden');
data1Input.setAttribute('name', 'data1');
data1Input.setAttribute('value', 'some-data-here');
checkAccountStatusForm.appendChild(data1Input);
var data2Input = document.createElement('input');
data2Input.setAttribute('type', 'hidden');
data2Input.setAttribute('name', 'data2');
data2Input.setAttribute('value', 'some-other-data-here');
checkAccountStatusForm.appendChild(data2Input);
document.body.appendChild(makeshiftAjaxReplacement);
makeshiftAjaxReplacement.submit();
document.body.removeChild(makeshiftAjaxReplacement);
But how to achieve the same thing using Ajax?
This is as far as I've got... but it's definitely not working:
Approach using Ajax
var myAjaxXHR = new XMLHttpRequest();
var serverSideScript = '/server-side-script.php';
var myAjaxForm = new FormData();
myAjaxForm.append('data1', 'some-data-here');
myAjaxForm.append('data2', 'some-other-data-here');
myAjaxXHR.open('POST', serverSideScript, true);
myAjaxXHR.send(myAjaxForm);
myAjaxXHR.onreadystatechange = function() {
if ((myAjaxXHR.readyState === 4) && (myAjaxXHR.status === 200)) {
window.alert('Ajax Successful');
}
};