0

I need to execute the same code in jQuery multiple times so i decided to make my own jQuery function.

It looks like this so far:

                jQuery.fn.extend({
                fooFunction: function () {
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: "includes/thescript.php",
                        success: function (data)
                        {
                            $(this).html(data);
                        }, complete: function () {
                            // do sth
                        }
                    });
                    return $(this);
                }
            });

But now i have the problem, that "this" seems to refer to the wrong instance, while using it here in the success function "$(this).html(data);".

When i use the ID instead, e.g. $("#TheID").html(data); it works, but why not with "this"?

Between: I call the function with: $("#TheID").fooFunction()

mademyday
  • 83
  • 2
  • 9
  • 1
    Possible duplicate of [$(this) inside of AJAX success not working](http://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) – Paul Roub Apr 05 '16 at 14:04

3 Answers3

2

The issue is that the scope of this changes when you're inside the anonymous function you provide to the success parameter. To solve the problem you can store the this reference from the outer scope in a variable, like this:

jQuery.fn.extend({
    fooFunction: function () {
        var $el = $(this);
        $.ajax({
            type: "POST",
            cache: false,
            url: "includes/thescript.php",
            success: function (data) {
                $el.html(data);
            }, 
            complete: function () {
                // do something
            }
        });
        return $el;
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.

For more information visit this link $(this) inside of AJAX success not working

Community
  • 1
  • 1
Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62
0

At the beginning of the function cache $(this) and then use that instead.

this in the function reference to the function context not the element targeted.

Try this.

jQuery.fn.extend({
    fooFunction: function () {
        var $this = $(this);
        $.ajax({
            type: "POST",
            cache: false,
            url: "includes/thescript.php",
            success: function (data)
            {
                $this.html(data);
            }, complete: function () {
                // do sth
            }
        });
        return $this;
    }
});
GillesC
  • 10,647
  • 3
  • 40
  • 55