javascript - How to ensure my Ajax call is finished before calling a new function inside window.onload? -
i not utilize json or jquery @ point - plain vanilla javascript answers please (i've found bunch of answers problem on se, include jquery or json).
i have 2 functions within window.onload=function(){...
event handler. first function fillarray(from,to)
ajax phone call of form:
function fillarray(from,to){ request = createrequest(); if (request == null) { return; } var url= "ajax_retrievenames.php?indexfrom=" + + "&indexto=" + to; request.open("get", url, true); request.onreadystatechange = populatearray; request.send(null); } function populatearray(){ var xmlfrag=null; if (request.readystate == 4) { if (request.status == 200) { xmlfrag = request.responsexml; for(var i=indexfrom; i<=indexto; i++){ fcarray[i]=new array(); var f=xmlfrag.getelementsbytagname("first")[i].childnodes[0].nodevalue; var l=xmlfrag.getelementsbytagname("last")[i].childnodes[0].nodevalue; fcarray[i][0]=f; fcarray[i][1]=l; } }else{ return; } }else{ return; } }
the sec function shownextname()
deals formatting , displaying elements of next (in case first) sub-array. @ point, var arrayindex
set 0:
function shownextname(){ displayquestion() // deals page formatting document.getelementbyid('firstname').innerhtml=fcarray[arrayindex][0]; document.getelementbyid('lastname').innerhtml=fcarray[arrayindex][1]; updatearrayindex(); // counter increments variable arrayindex }
my problem script goes sec function, shownextname()
, before completing ajax phone call , populating array. can recolve incorporating timer between 2 functions that's clumsy. there improve way create sure not shownextname()
or leave window.onload
until ajax phone call completed , array populated?
call shownextname
in success callback (populatearray
). since ajax asynchronous, need exectute logic depending on when readystate
4 did in populatearray
function.
function populatearray(){ var xmlfrag=null; if (request.readystate == 4) { if (request.status == 200) { xmlfrag = request.responsexml; for(var i=indexfrom; i<=indexto; i++){ fcarray[i]=new array(); var f=xmlfrag.getelementsbytagname("first")[i].childnodes[0].nodevalue; var l=xmlfrag.getelementsbytagname("last")[i].childnodes[0].nodevalue; fcarray[i][0]=f; fcarray[i][1]=l; } shownextname(); }else{ return; } }else{ return; } }
javascript ajax
No comments:
Post a Comment