Skip to content Skip to sidebar Skip to footer

Use Ajax To Populate Cordova Database

following the official documentation of phonegap / cordova on handling databases, I have implemented the code and it worked well for me for a single table, getting JSON data types

Solution 1:

By default, all $.ajax requests are sent asynchronously, so i suppose the problem is that

transactions.push("INSERT INTO people...

invokes after writing to database is done.

You can put second request at the end of "done" function of first request, and writing to database at the end of "done" function of second request. It looks quite ugly, even if you split it in several functions, but it should work.

Using of $.Deferred improve a little how code looks like: http://api.jquery.com/category/deferred-object/

jQuery.ajax "async" (which you can set to "false") setting is deprecated since JQuery 1.8, so it's not a good option. https://api.jquery.com/jQuery.ajax/

UPDATE. Code for the first option (only important part):

functionupdate()
{
    jqxhr = $.ajax( "http://www.example.com/file.php?id=100" )
    .done(function(data) 
    { 
        data = JSON.parse(data);
        var elementsCount = data.elements.length;
        $.each(data.elements,function(index, item)
        {
            transactions.push("INSERT INTO elements VALUES('"+ item.id + "','"+ item.name + "','"+ item.tel + "','"+ item.mail +"')");
            if (index == elementsCount - 1) //making sure all elements are added to array
            {
                updateSecond();
            }
        });
    });
}

functionupdateSecond()
{
    jqxhr = $.ajax( "http://www.example.com/file.php?id=200" )
    .done(function(data) 
    { 
        data = JSON.parse(data);
        var elementsCount = data.people.length;
        $.each(data.people,function(index, item)
        {
            transactions.push("INSERT INTO people VALUES('"+ item.id + "','"+ item.name + "','"+ item.nick + "','"+ item.gender +"')");
            if (index == elementsCount - 1) //making sure all elements are added to array
            {
                dbWrite();
            }
        });
    });
}

functiondbWrite()
{
    var db = window.openDatabase("Database", "1.0", "Example", 2097152);
    db.transaction(populateDB, errorCB, successCB);
}

Code definitely doesn't look like ideal, but it should work properly.

Post a Comment for "Use Ajax To Populate Cordova Database"