0

In the following function, how can I tell JS to wait for the return of my ajax call before proceeding with sql transaction. The following sample code currently get the data properly, but the sql transaction is executed before the AJAX call populate my employees []

I try to place sql operation after succes but I got the following error

Uncaught DOMException: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed.

Here is part of the code

var addSampleData = function (tx, employees) {

        var employees = [];

$.ajax({
            url: 'my-path-to-my-json-answer',
            success: function (value, status) {
            employees.push(value);
        },
        error: function (XMLHttpRequest, textStatus, exception) {
            console.log("Connection with the server fail.\n" + textStatus + 'status is: ' + exception);
        }
    });

        var l = employees.length;

        var sql = "INSERT OR REPLACE INTO leaderboard " +
        "(id, uFname, uLname, uRegion, uCountry, uScore) " +
        "VALUES (?,?,?,?,?,?)";

        var e;

        for (var i = 0; i < l; i = i + 1) {
            e = employees[i];
            tx.executeSql(sql, [e.id, e.uFname, e.uLname, e.uRegion, e.uCountry, e.uScore],
                function () {
                    console.log('INSERT success');
                },
                function (tx, error) {
                    console.log('INSERT error: ' + error.message);
                });
        }   

    }

Any suggestion to improve that code are welcome.

4
  • Use .done search jquery for promise syntax Commented Dec 12, 2016 at 16:07
  • trigger the SQL call from your "success" function (either code directly in the function, or put in a call to another function which runs the query). This callback is only executed once the response is received from the server. Ajax is asynchronous. Conceptually, you can't "tell other code to wait", you can simply "not execute it until ajax is finished" - and the only way to do that is through the "success" callback (or via .done() if you use the Promise interface). Commented Dec 12, 2016 at 16:13
  • In addition to the above: Why do you re-define parameter employee? You should also consider this, depending on how your entire application behaves. Commented Dec 12, 2016 at 16:30
  • good point @Ceredig, the employees var should not be passed as a parameter in the function. Code works now, since I execute my websql transaction after success. Commented Dec 12, 2016 at 20:37

1 Answer 1

0

It is because Ajax calls are asynchronous and browser starts a separate thread for the ajax call. In order to execute your SQL query after ajax call completion, put the code you want to SQL query code in success method of ajax as below...

jQuery.ajax({
        type:"post",
        dataType:"json",
        url: myAjax.ajaxurl,
        data: {action: 'submit_data', info: info},
        success: function(data) {
            //do your SQL work here...
            console.log('doing SQL work');
        },
        error: function(data) {
           console.log('boo...boo...');
        },
    });
Sign up to request clarification or add additional context in comments.

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.