Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax (this) not working

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'.

like image 610
Adola Avatar asked Jul 21 '12 19:07

Adola


1 Answers

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%');
like image 88
BishopZ Avatar answered Oct 04 '22 02:10

BishopZ