The thing is I'm currently using an ajax call to grab some data from an html file, and populate a list of buttons on success from the data it finds in the html file. This part is working fine. However, in the same function that populates the list of buttons, im trying to make it so that each button, once clicked, performs another ajax to a url that is specific to that button. Since i have the list of urls in an array, i use a for loop to populate the list of buttons, and in the same for loop, i add an on click function to each button. The problem I'm having is that when i click a button, it only retrieves the last URL regardless of which button was clicked.
heres my code:
for(var i = 0; i < tools.length; i++){
name = tools[i][0];
url = tools[i][1];
var id = "";
for(var j = 0; j < name.length; j++){//remove periods from ids
if(name.charAt(j) != '.'){
id += name.charAt(j);
}
}
//populate the list of tools
$("#tools").append("<li>"
+ "<button class='button button-primary buttons' id='"+id+"' type='button'>"+name+"</button>"
+ "</li>"
);
// alert(url);
$("#"+id).on('click', function(event) {
$.ajax({
url: url,
type: 'GET',
dataType: 'xml',
success: processXML
});
});
};
function processXML(xml){
var title = $(xml).find('title').first().text();
alert(title);
}
I researched a bit and found this response: https://stackoverflow.com/a/2687739/4312572
however creating a function(i) that did everything in my for loop, then calling the function inside the for loop didn't change anything. It still used the last value for i.
I need each button to make its own ajax call, but the buttons themselves are populated by the success function of a previous ajax call.
How should i set this up to achieve what i need? Thanks in advance for any help!