Martin Martin - 4 years ago 83
Javascript Question

Jquery callback function variables always local?

Why cant i set the $('#temizle').innerHTML to string 'Temizlendi';
The code blow just doesnt work. But in the line before end i can set it. I'm confused.

$('#temizle').click(function(){
$.post('OdbcConnection.php',
{islem: 'Temizle'},
function(data, status){
if(status == 'success'){
alert(status);
$('#temizle').innerHTML = 'Temizlendi';
}else{
this.innerHTML = 'Hata Var';
}
});
//this.innerHTML = 'Temizlendi';
});

Answer Source

The short answer is because innerHTML is a native DOM node method, not a jQuery method, therefore calling it on a jQuery object such as $('#temizle') does nothing but set a new innerHTML property in the jQuery object. It works outside of your $.post call because this inherits a native DOM node, not a jQuery object.

Try using the $.html() method instead of innerHTML:

$('#temizle').html('Temizlendi');

Alternatively, outside of the scope of your $.post could also be re-written from this.innerHTML to $(this).html(), as wrapping this would convert it into a jQuery object.

If you absolutely have to use innerHTML rather than the jQuery method, as mentioned in other answers you can also get a DOM node from a jQuery object by using the get() method or accessing the node at the 0 index of the jQuery object:

$( '#temizle' ).get(0).innerHTML = 'Foo';
$( '#temizle' )[0].innerHTML = 'Bar';

Although that would sort of defeat the purpose of using jQuery.

Another thing to remember is that the value of this depends on the current scope, so this will not be equal to your element when it is called inside of your $.post. To get around this, you could cache your element outside of the scope of your post call so you can easily refer back to it within the callback:

$('#temizle').click(function(){
    var $el = $( this );

    $.post('OdbcConnection.php',
        {islem: 'Temizle'},
        function(data, status){
            if(status == 'success'){
                alert(status);
                $el.html( 'Temizlendi' );
            }else{
                $el.html( 'Hata Var' );
            }
        });

    //$el.html( 'Temizlendi' );
});

To get a better understanding of this, I'd highly recommend checking out the MDN reference on it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download