I am trying to fetch data from select options from a website with javascript. The purpose is to get a list of zones in my country from a website that has them.
My problem is as follows : The list is displayed hieraquically in 3 selects, where the first one has a loaded list of the first level zones which I can get just fine, but then when I $.each
the second list by calling the ajax request used by the website with a flag of the current top level zone, all the subzones are assigned to the last top zone. It seems like the overall script is not waiting for the ajax calls to be made, so when they get made the current ID is the last one on the top level list. How can I go around this? Is it possible for example to access the data
sent in the request within the done()
callback?
var current_d = 0;
var zones = {
d : [],
c : [],
f : []
};
$.each($('#ddState>option:gt(0)'), function(i, v) {
zones.d.push({name : $.trim($(v).html()), id : parseInt($(v).attr('value'))});
current_d = parseInt($(v).attr('value'));
var data = {};
data.Action = '***';
data.ID = current_d; // This is the ID flag for the ajax request
$.ajax({
type: 'POST',
url: '***',
data: data,
cache: false,
dataType: 'json'
})
.done(function(response) {
$.each(response, function(i, v) {
zones.c.push({name : v.Name, id : parseInt(v.Id), parent_id : current_d});
console.log(current_d); // When it gets here the flag has changed to the last ID in the previous list
});
});