1

I have a problem when trying to store the results of a select query into an array with java script . the problem is that inside the function the array is containing the right values but outside it's empty , even when i used a global var it's still empty !!!

db.transaction(function (transaction) {
    var sql = "SELECT * FROM Question where idEnq=" + idEn;

    transaction.executeSql(sql, undefined, function (transaction, result) {
        var res = document.getElementById('results');
        res.innerHTML = "<ul>";
        if (result.rows.length) {
            for (var i = 0; i < result.rows.length; i++) {
                var row = result.rows.item(i);
                ch[i] = new qu(row.id, row.text, row.type);
                res.innerHTML += '<li>' + row.id + '&nbsp;' + ch[i].text + '&nbsp;' + ch[i].type + '</li>';
            }
            tablo = ch;
        } else {
            alert("No choices");
            res.innerHTML += "<li> No choices </li>";
        }

        res.innerHTML += "</ul>";
    }, onError);
}); // here the ch and the tablo array are empty
2
  • You really need to start indenting your code properly!!! Commented May 6, 2012 at 16:27
  • 1
    Don't put idEn directly in the query text, that is what bind variables (the second argument for executeSql) is for. Commented May 6, 2012 at 16:31

2 Answers 2

4

You are using asynchronous functions. Anything that wants to use the data "returned" by those functions need to be in the callback. Of course you can assign this data e.g. to a global variable, but that variable will only have the value after the callback has run (asynchronously).

Sign up to request clarification or add additional context in comments.

4 Comments

sorry but I'm new to JS and I don't know how to use the callback !!
Move your code that is currently after the db.transaction(...) call inside the callback, i.e. after res.innerHTML += "</ul>";
this code is already inserted into a function that returns the array , do i have to add the callback parameter as follow : function GetQuest(idEn,callback) {...... ............... return tablo;} and then what ?
I followed the answer given here stackoverflow.com/questions/9933877/… but an error occurs saying 'Uncaught ReferenceError: callback is not defined' so what should I do ??
0

you're new so have look here http://pietschsoft.com/post/2008/02/JavaScript-Function-Tips-and-Tricks.aspx there's a part talking about calling JavaScript Function asynchronously

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.