I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using:
setTimeout(function() {}, 100);
Below is a snippet of my code:
function change_country(id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
document.getElementById("continent").value = data.continent;
document.getElementById("country").value = data.country;
}
xmlhttp.open("GET", "request_country_change.php?id=" + id, true);
xmlhttp.send();
}
}
This excerpt serves as an example and is not part of the original code. It aims to demonstrate a form that undergoes changes. In this scenario, it fetches and populates a select field with all continents, followed by selecting the continent and countries based on the provided id. However, it loads the list in the select fields ahead of running the JavaScript portion.
document.getElementById("continent").value = data.continent;
document.getElementById("country").value = data.country;
The execution order seems off. While placing an alert or setTimeout in between rectifies the problem, I seek alternative solutions to address it.