1

I am making a ajax call and depending on the result I will swop my img, and fire an alert. Neither of which are happening, but I can't understand why this isn't happening??

  var myd = "";
         $.ajax({                 
              url:"urlencode.php",
              data: data,
      type: "POST",
      success: function(data) { 
                  myd = $('<span />').html(data).find("#Result").text();
                  console.log(myd);
                  if (myd == 'c5:3;'){$(this).attr('src','lightbulboff.png')};    
                },
              error: function (request, status, error) 
               {   
                alert(request.responseText);
                }
                });

1 Answer 1

1

The problem is that the this value in your callback is changed; it's now the jqXHR object. The simplest way to fix this is to bind your callback to the current this value:

function(data) { 
    myd = $('<span />').html(data).find("#Result").text();
    console.log(myd);
    if (myd == 'c5:3;'){$(this).attr('src','lightbulboff.png')};    
}.bind(this)

This will "pre-set" the this value of your callback. Just note that this isn't available in IE8, and so you'd need to shim it. A shim is available here


The other way to fix this is to "save" the current value of this. Something like:

var self = this;
$.ajax(......
    success: function(){
        myd = $('<span />').html(data).find("#Result").text();
        console.log(myd);
        if (myd == 'c5:3;'){$(self).attr('src','lightbulboff.png')};    

Your callback will "close over" the self variable, and still have access to it when the callback runs.

Sign up to request clarification or add additional context in comments.

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.