Migua
Migua

Reputation: 555

issue with $ajax async false

I have this code:

 for(var i in dataJson){    
            direcc=dataJson[i].dir  ; 
            id=dataJson[i].id   ;

    $.ajax({
            url: 'http://dev.virtualearth.net/REST/v1/Locations?query=' + direcc + '&key=mykey&jsonp=?',
           dataType: 'json',
       async: false,
           success: function(result) {

             loc = result.resourceSets[0].resources[0].point.coordinates;
             direcc=result.resourceSets[0].resources[0].address.formattedAddress;
             lat=loc[0];
             long=loc[1];


          $("#bing").append('latitudeBing:' + lat + '<p>longitudeBing:' + long+'$$$$$$'+id);
 }
   });

The problem is that I want to write latitude+longitude+ id, but when it writes the id is the last for all of them ( id goes from 1-200, and in all coordinates appears 200).

The original function was $getjson and i changed it to make the $ajax call async:false, but that doesn't fix my problem.

Could anybody help me please? Thank you very much!!

Upvotes: 1

Views: 276

Answers (1)

Gromer
Gromer

Reputation: 9931

Edited with the correct answer now.

Fiddle to show the concept

for(var i in dataJson){    
    var direcc = dataJson[i].dir; 
    var id = dataJson[i].id;
    makeAjaxCall(direcc, id);
}

function makeAjaxCall(direcc, id) {
    $.ajax({
        url: 'http://dev.virtualearth.net/REST/v1/Locations?query=' + direcc + '&key=mykey&jsonp=?',
        dataType: 'json',
        async: false,
        success: function(result) {
            loc = result.resourceSets[0].resources[0].point.coordinates;
            direcc=result.resourceSets[0].resources[0].address.formattedAddress;
            lat=loc[0];
            long=loc[1];
            $("#bing").append('latitudeBing:' + lat + '<p>longitudeBing:' + long+'$$$$$$'+id);
        }
    });
}

This puts the "current" direcc and id in the scope of the makeAjaxCall function. The Fiddle I added is just showing how.

Also, no need to keep the async: false, around, so feel free to remove that if you want.

Upvotes: 1

Related Questions