0

Possible Duplicate:
Javascript closure inside loops - simple practical example


I am using webservice to get the data in the form of JSON by using javascript and want to store that data in Sqlite Database. here i used for loop to store data one by one in Database by executeSql Query. But problem is function inside the for loop getting "i" value out of scope means showing undefined. I am trying to solve this problem by last 5 days. Any suggestion ?

Thanks

function GetGeoValues() {
    $.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something", function (Jdata) {
        var geoid = new Array();
        var geoname = new Array();
        var i;
        for (i = 0; i < Jdata.vact_geography.length; i++) {
            geoid.push(Jdata.vact_geography[i].geo_id);
            geoname.push(Jdata.vact_geography[i].geo_name);
            db.transaction(function (transaction) {
                alert(geoid[i]); // here i showing undefined
                transaction.executeSql('INSERT INTO vact_geography VALUES(' + parseInt(geoid[i]) + ',"' + geoname[i] + '")');
            });
        }
    });
}
Community
  • 1
  • 1
Manzur Husain
  • 185
  • 1
  • 4
  • 16

2 Answers2

0

Here inner function and outer function concept is considered. So the outer function have the var i. But in inner function i is not defined. Thats y its throwing error as "undefined"

Nagarajan
  • 432
  • 3
  • 12
  • 28
  • That is incorrect. The inner function is a closure and has access to all variables defined in higher scopes. The problem is that upon invocation of the function, the value of `i` is not a valid index in the array. – Felix Kling Sep 19 '11 at 10:27
0

I'm not sure, but this can happen, if function(transaction) executed in asynchronous mode. In this case variable i after for loop is finished must be equals to Jdata.vact_geography.length, and, as result geoid[i] equals to undefined. To workarround this try next:

function GetGeoValues() {
  $.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something",
         function(Jdata) {
           var geoid=new Array();
           var geoname=new Array();
           for(var i=0;i<Jdata.vact_geography.length;i++) {
             geoid.push(Jdata.vact_geography[i].geo_id);
             geoname.push(Jdata.vact_geography[i].geo_name);
           }
           db.transaction(function(transaction) {
             for(var i=0;i<geoid.length;i++) {
               alert(geoid[i]); // here i showing undefined
               transaction.executeSql('INSERT INTO vact_geography VALUES('+parseInt(geoid[i])+',"'+geoname[i]+'")');
               // All INSERT's executed in one transaction
             }
           });  
         }
       ); 
}
Andrew D.
  • 8,130
  • 3
  • 21
  • 23
  • can u please help me how to write SELECT query inside FOR loop using javascript in phonegap app – nida Oct 08 '13 at 10:14