javascript - Postponing window.location to allow time for AJAX -


i have index page i'd use set local database before moving on page. however, whenever have window.location code activated none of other functions run, when comment out other functions run fine. ideas causing , how can both functions , window.locations work? code follows:

<script>         var db = window.opendatabase("db1", "", "db", 1024 * 1000)             createdb(); //creates local database tables             loadroutelist(); //queries web server database using ajax , inserts routes             window.location = 'application.html'; </script> 

functions used:

function createdb() {     db.transaction(function (tx) {         tx.executesql('create table if not exists routes(id integer primary key, routeid text, customerid text, stopseq text, driverid text)', []);     }); }; function loadroutelist() { var dataobject = {     postdesignator: 'routes', }; $.ajax({     url: 'http://url.php',     data: dataobject,     datatype: 'json',     type: 'post',     success: function (result) {         (var = 0, len = result.records.length; < len; ++i) {             var route = result.records[i].record;             insertroute(route.routeid, null, null, null);         }     } }); } 

by definition, ajax asynchronous, if run functions , don't wait them completed, code go on without waiting them. arrive @ point location changes due line. have wait until requests done before going on, , have change code inside functions. if post them you.

edit

in opinion, best way pass callback function:

function createdb() {     db.transaction(function (tx) {         tx.executesql('create table if not exists routes(id integer primary key, routeid text, customerid text, stopseq text, driverid text)', []);     });     //if piece of code async should read docs , check how call function after query executed }; function loadroutelist(callback) {     var dataobject = {         postdesignator: 'routes',     };     $.ajax({         url: 'http://url.php',         data: dataobject,         datatype: 'json',         type: 'post',         success: function (result) {             (var = 0, len = result.records.length; < len; ++i) {                 var route = result.records[i].record;                 insertroute(route.routeid, null, null, null);             }             if(callback) {                 callback();             }         }     }); } 

and use way:

var db = window.opendatabase("db1", "", "db", 1024 * 1000)     createdb(); //creates local database tables     loadroutelist(function() {         window.location = 'application.html';     }); 

Comments