Reputation: 2162
I have this:
$.ajax({
url: "blah.php?something",
dataType: "json"
....
success: function(x){
for(i in x.artists) {
addbutton.text(x.artists[i].name).click(function(){
load(x.artists[i].name)
});
}
});
It's for a music player, and this is a suggestions engine. It loads artist names through AJAX, in JSON format from the PHP file, as you can see.
The problem is with the click() function which is supposed to load songs related to that artist. When the function gets called (ie the button gets clicked), instead of passing the artist's name as a string to load(), it passes x.artists[i].name, which of course is invalid outside of the ajax success function.
How would I go about solving this?
Thanks, Fela
Upvotes: 0
Views: 411
Reputation: 58521
Seeing as how you are setting the text value first - you can just re-use that if you like:
addbutton.text(x.artists[i].name).click(function(){ load($(this).text()) })
Upvotes: 1
Reputation: 82893
Change your addButton click handler to:
addbutton.text(x.artists[i].name).click(function(){
load($(this).text())
});
or change the for loop to as follows(in case the text of the button is changed by some other code before the button is clicked.):
for(i in x.artists) {
var artistName = x.artists[i].name;
addbutton.text(artistName ).click(function(){
load(artistName) ;
});
}
Upvotes: 1