0

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

3 Answers 3

1

Replace

load(x.artists[i].name) 

with

load($(this).text()) 
Sign up to request clarification or add additional context in comments.

Comments

1

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) ;
  }); 
}

Comments

1

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()) })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.