0

I m working on phonegap product using jquery and jquery mobile, the scenario is, when user is logging in for first time, we sync all the data and after done we forward user to another view. The items are retrieved in json format from server. Here are the portion of my code. I have called the webservice and the response is returned as JSON objects in response variable.

$(response.data.module.registration).each(function(k,v){
    //insert into app's sqlite database
});

$(response.data.module.attendance).each(function(k,v){
    //insert into app's sqlite database
});

$(response.data.items.grocery).each(function(k,v){
    //insert into app's sqlite database
});

//and so on. There could be many rows in each loop above.

My question is how to know all rows has been inserted from the loop so that I can forward user to restricted area.

more precisely, how to know all JSON object has been iterated successfully?

What i tried is put counter in each loop and check if sum of all the counters is equal to total items we are iterating. But this didn't work the sum of all the counters are readily available before all items are inserted.

EDIT

Here is my helper function that inserts record into sqlite db. This didn't work, user was logged in before all data are inserted. Can you tell me where I went wrong

var sqlhelper = {
 insertJSONData:function(tablename,data,callback){
          var dfrd = $.Deferred(); 
          var fields=sqlhelper.separateFieldData(data,"field");
          var dataval=sqlhelper.separateFieldData(data,"value");
          sqlhelper.db.transaction(function(tx) {
            var sqlquery='INSERT INTO '+tablename+' ('+fields+') values('+dataval+')';
            console.log(sqlquery);
             tx.executeSql(sqlquery,[],function(tx,result){ 
                dfrd.resolve(result); 
                console.log('Success'); 
            },sqlhelper.errorCB);
              if(callback!=undefined){
                callback();
              }
          });

          return dfrd.promise(); 
    }
}

And here is the code that fetches server response

function defObj1()
{
    if(typeof response.data.module.registration!="undefined"){
              $(response.data.module.registration).each(function(i,e){
                    var data = {
                                'reg_id':     e.reg_id,                                                       
                                'reg_name':  e.reg_name,                                                                   
                                'reg_desc':   e.reg_desc,                                                                           
                                'reg_status':    e.reg_status
                    };
                    sqlhelper.insertJSONData('tbl_registration',data);
                }); // end of each loop

    }
}

function defObj2()
{
    if(typeof response.data.items.grocery!="undefined"){
              $(response.data.items.grocery).each(function(i,e){
                    var data = {
                                'grocery_id':     e.grocery_id,                                                       
                                'item_name':  e.item_name,                                                                   
                                'item_qty':   e.item_qty,                                                                           
                                'item_unit_price':    e.item_unit_price
                    };
                    sqlhelper.insertJSONData('tbl_grocery',data);
                }); // end of each loop

    }
}


$.when(defObj1() ,defObj2()).done(function(a1,a2){
    //sync complete so login user
    doLogin();
})

Thanks

WatsMyName
  • 4,240
  • 5
  • 42
  • 73
  • there is $(el).each(function(index, elem){}) in https://api.jquery.com/each/ – Sherali Turdiyev Aug 31 '15 at 10:16
  • @SheraliTurdiyev, Not my answer, I have already done that, please look my question again – WatsMyName Aug 31 '15 at 10:34
  • @Quentin How come this question relate to the one you specified??, The problem mine starts right after all the jquery ajax request response is retrieved. So I don't think this is duplicate – WatsMyName Aug 31 '15 at 10:39
  • @WatsMyName — Because inserting into an SQLite database is also going to be using an asynchronous function. It's the same problem, you are just substituting SQL for HTTP. – Quentin Aug 31 '15 at 10:40
  • @WatsMyName. check my answer. maybe, it will work – Sherali Turdiyev Aug 31 '15 at 11:32
  • @Quentin, please have a look at EDIT portion of my post. – WatsMyName Sep 02 '15 at 05:32
  • @WatsMyName — So that's an asynchronous function, so the problem is still a duplicate of the other question. – Quentin Sep 02 '15 at 06:50
  • @Quentin , In edited part I have done as directed in the link you specified, but it didn't work. Just wanted to know where am I going wrong – WatsMyName Sep 02 '15 at 08:59
  • `defObj1` and `defObj2` don't have return statements. You have to pass promises to `when()`, not `undefined`. – Quentin Sep 02 '15 at 09:04
  • @Quentin `sqlhelper.insertJSONData` in both the function returns the promises, if you meant that – WatsMyName Sep 02 '15 at 09:06
  • You aren't passing the return value of `sqlhelper.insertJSONData` to `when()` (you aren't doing anything with the return value of `sqlhelper.insertJSONData`). – Quentin Sep 02 '15 at 09:07

1 Answers1

1

try this. (Edited)

var isValid = true, i = 0, sum, callback = function () {
    //if all inserting is successfully  it is called 
};

...

$(response.data.module.registration).each(function (k, v) {
    //insert into app's sqlite database
    var data = {
        'reg_id': e.reg_id,
        'reg_name': e.reg_name,
        'reg_desc': e.reg_desc,
        'reg_status': e.reg_status
    };
    sqlhelper.insertJSONData('tbl_registration', data, function (data) {
        if (!data) {
            isValid = false;
            sum++;
        }
        i++;//onSuccess function
        checkLast(i);//call this lastly method or each
    }, function () {
        i++;//onError function
    });
});
...
//other codes is identical logic

...

function checkLast(i) {
    if (i == sum) {
        callback();
    }
}

...

I have added successCallbak and errorCallback to your sqlhelper

var sqlhelper = {
    insertJSONData: function (tablename, data, successCallbak, errorCallback) {
        var dfrd = $.Deferred();
        var fields = sqlhelper.separateFieldData(data, "field");
        var dataval = sqlhelper.separateFieldData(data, "value");
        sqlhelper.db.transaction(function (tx) {
            var sqlquery = 'INSERT INTO ' + tablename + ' (' + fields + ') values(' + dataval + ')';
            console.log(sqlquery);
            tx.executeSql(sqlquery, [], function (tx, result) {
                dfrd.resolve(result);
                if (successCallback) {
                    successCallback(result);
                }
                console.log('Success');
            }, sqlhelper.errorCB);
            if (errorCallback) {
                errorCallback();
            }
        });

        return dfrd.promise();
    }
}
Sherali Turdiyev
  • 1,745
  • 16
  • 29