This question may be a bit lengthy, so I'll do my best to provide an explanation. There are two JavaScript functions that need to execute after the page loads - let's call them function1() and function2().
function1() uses AJAX to fetch data from the database, which is then displayed in a div based on the retrieved information. It also returns the data once the function completes.
function2() relies on this database value to run correctly, so it must wait for function1() to finish before proceeding. Despite my efforts, there seems to be an issue with the code. Here's a basic outline:
function function1() {
if (some_cookie_exists) {
//execute some code
} else {
//send parameters through "POST"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var a = some_value_from_database;
// update div content
return a;
}
}
//send parameters
}
function function2(a) {
//perform actions based on the value of "a"
}
window.onload = function() {
var data = function1();
function2(data);
The issue arises when the var data turns out to be undefined. While function1() retrieves the data successfully as planned, function2() fails to execute because it lacks the necessary value. Can someone help me figure out why this happens and suggest a solution?
NOTE: My knowledge is mostly limited to JavaScript (still learning), and I am unfamiliar with JQuery. If you propose using JQuery to resolve the issue, please explain the rationale behind it to assist me in understanding the solution.