Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this) doesn't work in a function

The following code loads html content from a file (i used this thread)

<script>
$.fn.loadWithoutCache = function (){
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
    success: function(data) {
        $(this).html(data);        // This is not working
      //$('#result').html(data);   //THIS WORKS!!!
        alert(data);           // This alerts the contents of page.html
    }
 });
}


$('#result').loadWithoutCache('page.html');

</script>

Please let me know what the problem is? I hope it's something stupid :)

Edit: CORRECT CODE

<script>
$(document).ready(function() {

$.fn.loadWithoutCache = function (){
 var $el = $(this);
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     context: this,
     success: function(data) {
     $el.html(data);
    }
 });
}

$('#result').loadWithoutCache('page.html');

});
</scipt>

Thanks Jon and everyone!

like image 367
Miro Avatar asked Dec 07 '22 18:12

Miro


2 Answers

The problem is that inside the success callback, this does not have the value you expect it to.

However, you do have access to this (with the expected value) inside loadWithoutCache itself. So you can achieve your goal by saving $(this) into a local variable and accessing it from inside the success handler (creating a closure).

This is what you need to do:

$.fn.loadWithoutCache = function (){
 var $el = $(this);
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data) {
        $el.html(data);
        alert(data);
    }
 });
}
like image 80
Jon Avatar answered Dec 10 '22 12:12

Jon


The callback (success) function runs when the response arrives, and it doesn't run in the scope of the loadWithoutCache method, as that has already ended.

You can use the context property in the ajax call to set the context of the callback functions:

$.fn.loadWithoutCache = function (){
  $.ajax({
    url: arguments[0],
    cache: false,
    dataType: "html",
    context: this,
    success: function(data) {
      $(this).html(data);
    }
  });
}
like image 38
Guffa Avatar answered Dec 10 '22 12:12

Guffa