The JavaScript file named test
.js is functioning properly when included in my HTML.
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
Now, I would like to refactor the code and consolidate certain parts into a single function.
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
This refactored version is saved as test2.js.
var xmlHttp;
function ready(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = ready;
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
However, upon testing, the test2.js
script encountered the following error:
test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
at XMLHttpRequest.ready (test2.js:4)
There is also a question regarding the proper order of statements for XMLHttpRequest:
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){ }
Some resources suggest an alternative sequence:
xmlHttp.onreadystatechange = function(){ }
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
For further clarification on this matter, refer to this webpage discussing proper ordering of xmlhttp statements.