1

I'm creating a app with phonegap. I use a little jquery and this plugin: html5sql.com/, for working with databases. My program runs in a strange order. I put some alerts in the code and wrote a comment behind each with the number the appear when I start the app on my device. Has anybody an idea why it doesn't run from top to bottom?

In global.js

  • I created a function that allows me to create a new object 'station'
  • I created a array with three ID's (relID)

    var station = function(id) {
        this.id = id;
    };
    
    var relID=new Array();
    relID[0]=2762378;
    relID[1]=2746459;
    relID[2]=2748307;

In index.js

  • I call dbStuff() with the relID Array as parameter
  • I save the return value in a variable called
  • I alert the brand property of the first object of the returned array (as a comment because of course its undefined at this time - but this is what I want to do when the code works)
var app = {

    initialize: function() {
        this.bindEvents();
        alert('vor dbStuff() aufruf');//1-----
        var relStations=dbStuff(relID);
        alert('nach dbStuff() aufruf');//6-----
        //alert(relStations[0].brand); ---UNDEFINED---
    },
    ...phonegap stuff...

In loaddb.js

  • I created a function 'dbStuff()' this should:
  • create new/open database and write stuff in
  • read from that database and write those values in a station object (for each relID[])
  • put all the station objects in a array and return it
function dbStuff(relID) {   
    //NEW ARRAY WHERE ALL STATION OBJECTS WILL BE SAVED  
    var relStations=[];

    alert('dbStuff() neues Array erstellt');//2-----

    //OPEN DATABASE AND WRITE DATA INTO
    try {
    html5sql.openDatabase("stations", "stations", 5 * 1024 * 1024);

    alert('open DB');//3-----

    $.get('js/db/stations.sql', function(dump) {

        alert('sbStuff() dump geladen');//7-----

        html5sql.process(
            dump, 
            function() { //Success
                alert('dump success');
            },
            function(error, failingQuery) { //Failure
                alert('dump fail'); //14-----
            }
        );

    });
    }
    catch (error) {
        alert("Error: " + error.message);
    }

    //GET DATA FROM DATABASE AND WRITE IT IN A STATION OBJECT
    //(FOR EACH ID IN 'relID' ARRAY)
    //FILL 'relStations' ARRAY WITH THE STATION OBJECTS AND RETURN IT
    for(var i=0; i<relID.length; i++){

        var stationa=new station(relID[i]);

        alert('dbStuff()-for neues station Objekt erstellt');//4-----

        //ARRAY WITH SQL STATEMENTS 
        var sqlarray = [
            {"sql" : "SELECT latitude FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.latitude=rs.rows.item(0).latitude;alert('SQL lat');//8-----
            }
            },
            {"sql" : "SELECT longitude FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.longitude=rs.rows.item(0).longitude;alert('SQL long');//9-----
            }
            },
            {"sql" : "SELECT brand FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.brand=rs.rows.item(0).brand;alert('SQL brand');//10-----
            }
             },
             {"sql" : "SELECT name FROM stations WHERE id=" + relID[i],
             "data" : [],
             "success" : function (tx, rs) {stationa.name=rs.rows.item(0).name;alert('SQL name');//11-----
             }
             },
             {"sql" : "SELECT federalstate FROM stations WHERE id=" + relID[i],
             "data" : [],
             "success" : function (tx, rs) {stationa.federalstate=rs.rows.item(0).federalstate;alert('SQL federalstate');//12-----
             }
             }
         ];

        try {html5sql.process(
            sqlarray,
             function () { //Success 
                 //alert('lat: ' + stationa.latitude + ', long: ' + stationa.longitude + ', brand: ' + stationa.brand + ', name:' + stationa.name + ', fedeeralstate:' + stationa.federalstate);
                 relStations[i]=stationa;
                 alert('Array füllen');//13-----
                 //alert(relStations[i].brand);
             },
             function () { //Failure
                alert('SQL FAIL');
             });}
             catch(error) {
            alert("Error: " + error.message);
        }

    }
    alert('return relStations'); //5-----
    return relStations;
}
Philipp M
  • 1,847
  • 7
  • 27
  • 38
Sven Keinath
  • 361
  • 3
  • 11

1 Answers1

0

That's probably because the callback functions have to wait for the script to end before they are being called.

The get-function after alert 3 will run, but the callback-function of it will run only when the server returned something to the get function, which can take a little time. In the meantime the code after the function will run, because it is an asynchronous request.
So you will see alert 4, 5 and 6, after that the request has been handled by the server, and the (anonymous) callback function gets called, which alerts alert 7.

Same for the other ajax call.

You could try the following. I moved some stuff into a function loadStations. This function will be called in the callback function of your get-call, but only in the case of a success.

function dbStuff(relID) {   
    //NEW ARRAY WHERE ALL STATION OBJECTS WILL BE SAVED  
    var relStations=[];

    alert('dbStuff() neues Array erstellt');//2-----

    //OPEN DATABASE AND WRITE DATA INTO
    try {
    html5sql.openDatabase("stations", "stations", 5 * 1024 * 1024);

    alert('open DB');//3-----

    $.get('js/db/stations.sql', function(dump) {

        alert('sbStuff() dump geladen');//7-----

        html5sql.process(
            dump, 
            function() { //Success
                alert('dump success');

                return loadStations(relID);
            },
            function(error, failingQuery) { //Failure
                alert('dump fail'); //14-----
            }
        );

    });
    }
    catch (error) {
        alert("Error: " + error.message);
    }
}

function loadStations(relID) {

    //GET DATA FROM DATABASE AND WRITE IT IN A STATION OBJECT
    //(FOR EACH ID IN 'relID' ARRAY)
    //FILL 'relStations' ARRAY WITH THE STATION OBJECTS AND RETURN IT
    for(var i=0; i<relID.length; i++){

        var stationa=new station(relID[i]);

        alert('dbStuff()-for neues station Objekt erstellt');//4-----

        //ARRAY WITH SQL STATEMENTS 
        var sqlarray = [
            {"sql" : "SELECT latitude FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.latitude=rs.rows.item(0).latitude;alert('SQL lat');//8-----
            }
            },
            {"sql" : "SELECT longitude FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.longitude=rs.rows.item(0).longitude;alert('SQL long');//9-----
            }
            },
            {"sql" : "SELECT brand FROM stations WHERE id=" + relID[i],
            "data" : [],
            "success" : function (tx, rs) {stationa.brand=rs.rows.item(0).brand;alert('SQL brand');//10-----
            }
             },
             {"sql" : "SELECT name FROM stations WHERE id=" + relID[i],
             "data" : [],
             "success" : function (tx, rs) {stationa.name=rs.rows.item(0).name;alert('SQL name');//11-----
             }
             },
             {"sql" : "SELECT federalstate FROM stations WHERE id=" + relID[i],
             "data" : [],
             "success" : function (tx, rs) {stationa.federalstate=rs.rows.item(0).federalstate;alert('SQL federalstate');//12-----
             }
             }
         ];

        try {html5sql.process(
            sqlarray,
             function () { //Success 
                 //alert('lat: ' + stationa.latitude + ', long: ' + stationa.longitude + ', brand: ' + stationa.brand + ', name:' + stationa.name + ', fedeeralstate:' + stationa.federalstate);
                 relStations[i]=stationa;
                 alert('Array füllen');//13-----
                 //alert(relStations[i].brand);
             },
             function () { //Failure
                alert('SQL FAIL');
             });}
             catch(error) {
            alert("Error: " + error.message);
        }

    }
    alert('return relStations'); //5-----
    return relStations;

}
Philipp M
  • 1,847
  • 7
  • 27
  • 38
  • Okay, but I want the code to break until the server returnes the file. The code runs and executes the alert(4, ...) before it turns back and execute the callback of the get - thats not what i want. – Sven Keinath Oct 16 '13 at 12:20
  • Then this could be moved to the callback function as well. There is probably a better alternative, but I don't know enough to make a suggestion at the moment. – Philipp M Oct 16 '13 at 12:22
  • Yes, I think you got it! Unfortunately I have to fight with this problem (http://stackoverflow.com/questions/12319809/application-error-the-connection-to-the-server-was-unsuccessful-file-andr) now so I don't know weather the first problem is solved for sure. Thank you anyway!!! – Sven Keinath Oct 16 '13 at 12:54
  • @SvenKeinath if this was the correct answer to your question, please accept it, so the question doesn't show up in the unanswered questions list and other users will know it has a solution. (you will even get some reputation for accepting an answer) – Philipp M Oct 23 '13 at 09:28