Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a Javascript function requires a value after an onload function is completed that gives the value?

I know its a long question, so allow me to explain as best as I can.

I have two javascript functions that I want to run after the page loads, we will call them function1() and function2().

function1() uses AJAX to retrieve information from the database that will arrange the contents in a div from the information obtained in the database. It also returns the contents from the database once the function has finished.

function2() requires the value from the database in order to run properly, so it needs to wait until function1() returns its value before function2() runs. Unfortunately my code is not working, and without going into too much detail, below is a schematic of the code:

function function1() {
if (some_cookie_exists) {
  //run some code
} else {
  //send parameters through "POST"
  xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var a = some_value_from_database;
    // change div content
  return a;
  }
  }
//sending parameters
}
function function2(a) {
//run code that depends on value of "a"
}

window.onload = function() {
var data = function1();
function2(data);

The error I get is that var data is undefined. function1() retrieves the data successfully, and runs as I intended it to, but function2() does not execute at all, because the value is missing. Can anyone figure out why I am getting this and how I should go about solving this?

NOTE: I am really only familiar with Javascript (still novice at that), I know essentially nothing about JQuery, so if you do use this to fix the code, please explain to me why this works (it will save me trouble later)

like image 892
Kevin O Avatar asked Dec 21 '12 08:12

Kevin O


1 Answers

AJAX is asynchronous (that's what the first A stands for). The results of the AJAX operation are not available in function1(), they're retrieved in the onreadystatechange handler that you attach to the XMLHttpRequest object. So it's not clear how you could be doing

var a = some_value_from_database;

in function1().

What you need to do is call function2() from the onreadystatechange handler.

If you post the actual implementation of function1 we may be able to provide more specific details.

UPDATE:

Here's how to call function2() when the value becomes available from the AJAX call:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var a = some_value_from_database;
        function2(a);
    }
}
like image 170
Barmar Avatar answered Sep 19 '22 00:09

Barmar