Reputation: 10338
I am attempting to create a function to request information about a Country ID in our database via ajax
, because that is how the data is represented in the address
table I query. That is, in the address
table, the id
of the country and not the country name is represented, and the actual country name is in another table that I query.
After I send the ajax
request, I create a string of the address I get. However, it's only updating the last value of the object and not all of them. Here is my coffeescript:
requests = Array()
for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
console.log(key)
console.log(val)
requests.push($.ajax
url: window.location.pathname
type: 'post'
dataType: 'json'
data: 'search_id=' + val + '&search_column=Id&sobject=Country__c&columns=["Name"]'
error: (jqXHR, textStatus, errorThrown) ->
alert('Error: ' + textStatus + ': ' + errorThrown)
success: (c_data, textStatus, jqXHR) ->
data[key] = c_data['Name']
console.log(c_data['Name'])
console.log(key)
)
defer = $.when.apply($, requests)
I omitted the defer.done
function. The result of the console.log information is as follows:
China P.R.
Country_of_Residence__c
China P.R.
Country_of_Residence__c
instead of being the expected
China P.R.
Correspondence_Country__c
China P.R.
Country_of_Residence__c
Is there an issue with my Coffeescript?
EDIT: It looks like it's something to do with the ajax
requests or pushing the ajax
requests to the requests
array. I added a couple console.log()
at the beginning of the function before I pushed the ajax
call, and it produced the following information:
Correspondence_Country__c
a063000000CZoZHAA1
Country_of_Residence__c
a063000000CZoZHAA1
Upvotes: 0
Views: 71
Reputation: 19040
$.ajax
is asynchronous (unless told otherwise, but you don't want to). Which means the loop will end before the ajax call is done. And when that ajax call finally end, "key" will be the last value of the array. (JS doesn't have block-scoping).
Use coffee's do
to keep the correct value.
for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
do (key) ->
# your code
Upvotes: 2