views:

686

answers:

1

I have a jQuery script:

$.ajax({
  url: "/scripts/secure/development/ajax.asp",
  type: "POST",
  dataType: "text",
  data: "cmd=addresses",
  success: function(msg){
    var arrRows = msg.split("#*#");
    for(i=0;i<arrRows.length;i++){
      var record_id = arrRows[i].split("|")[0];
      var address = arrRows[i].split("|")[1];

      getPoint(address,function(pnt){
        var latitude = pnt.lat();
        var longitude = pnt.lng();

        $.ajax({
          url: "/scripts/secure/development/ajax.asp",
          type: "POST",
          dataType: "text",
          data: "cmd=update&rec_id="+record_id+"&lat="+latitude+"&lng="+longitude,
          success: function(msg){
          }
        });
      });
    }
  }
});

function getPoint(address,callback){
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address,callback);
}

The script is designed to pull a delimited list of record_ids | addresses and loop through each one and get the geolocation of each address then update the record in the database with the lat and lng of the geo location.

My problem is this... In the second (inner) $.ajax call I need access to the record_id variable that I've defined just inside the for loop in order to update the correct record in the database however I can't seem to get access to that record_id variable inside the success function of the inner ajax post.

Please help! Thanks.

+1  A: 

You need to create a closure like this:

var callback = (function(record_id)
{
    return function(pnt)
    {
        var latitude = pnt.lat();
        var longitude = pnt.lng();

        $.ajax({
          url: "/scripts/secure/development/ajax.asp",
          type: "POST",
          dataType: "text",
          data: "cmd=update&rec_id="+record_id+"&lat="+latitude+"&lng="+longitude,
          success: function(msg){
          }
        });
      });
})(record_id);

getPoint(address, callback);
Greg
I need to access the record_id before the success: status of the ajax post is met... I need it in the data: portion of the ajax post itself.
Ryan
OK edited to do that instead
Greg