10

When attempting to access the '.box' class of the $container, using (this) inside of the ajax call doesn't work.

$container.on(
        "click",
        ".box",
        function(event){
            var description;
            if($(this)[0].style.width == '70%'){
                $(this).find(".resultData").fadeOut('slow');
                $(this).css('width', '18%');
            }else{
                $.ajax({
                    url:'scripts/php/fetchResultsData.php',
                    data: {action:value},
                    type: 'post',
                    dataType: 'json',
                    success: function(data){
                        description = data[0];
                        $(this).css('width', '70%');
                        $(this).append("\
                            <div class='resultData'>\
                                <div class='resultName'>" + $(this).find("p").html() + "</div>\
                                <div class='resultDesc'>" + description +"</div>\
                            </div>");
                        /*alert($(this).find("p").html());*/
                    }
                    })
            }
            $container.masonry('reload');
        }
    );

In case it's not clear what I'm trying to do, I'm attempting to change the css of dynamic elements. But for example,

$(this).css('width','70%');

Isn't adjusting the css at all. If I move it outside the ajax,success section, it works, but then I'm unable to get 'description'.

Oded
  • 463,167
  • 92
  • 837
  • 979
Adola
  • 460
  • 6
  • 21
  • As a rule of thumb, try not to use $(this), or at least, use it once. But if you need it multiple times, store it like: var $container = $(this) and use $container. This adds a bit of efficiency, but a lot more clarity. Just don't use $this, that, me all over the place, it defeats the purpose. – Azder Jul 21 '12 at 19:40
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Ivar Jun 10 '20 at 11:59

2 Answers2

17

You're close. 'this' in the context you are using it, refers to the ajax request rather than the thing that issued the event. To fix this, store a copy of this before making the ajax request:

                   }else{
                        var me = this;
                        $.ajax({
                            ...
                            success: function(data){
                                description = data[0];
                                $(me).css('width', '70%');
BishopZ
  • 5,909
  • 7
  • 38
  • 57
10

Just add this to your $.ajax call...

context: this,

...and it'll work.


$.ajax({
    context: this, // <-- right here
    url:'scripts/php/fetchResultsData.php',
    data: {action:value},
    type: 'post',
    dataType: 'json',
    success: function(data) { // ...