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

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


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);    }}


Do it with a callback.

function function1(callback) {    /* ... */    callback(data); // instead of return}var function2 = function(data) { // important: make "function2" a variable so that it can be passed as an argument later on    /* ... */}    window.onload = function() {    function1(function2); // important: no parentheses after function2, otherwise it would be executed right away}


Because ajax by definition is asynchronous, function2 will start executing before the ajax completes in function1. JQuery would be useful here, as you can place function2 in the success callback of the ajax call in function1.

So include JQuery in your HTML and the following JS should work:

$(function() {   //same as onload      function1() ;}function function1() {        $.ajax({              url: "url here",              type: "GET",               success: function(data) { // data is what is returned in ajax response                           // rearrange divs                            function2(data);                }           }););function function2(data) {}

More on the JQuery ajax function here: http://api.jquery.com/jQuery.ajax/