Ajax (this) does not work

When trying to access the ".box" class in the $ container using (this) inside the ajax call does not 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'); } ); 

If it is not clear what I am trying to do, I am trying to change the css of the dynamic elements. But for example

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

Does not configure css at all. If I translate it outside of ajax, the success section, it works, but then I cannot get a โ€œdescriptionโ€.

+6
source share
2 answers

You're close 'this' in the context that you are using refers to an ajax request, not what the event threw. To fix this, save a copy of this file before executing the ajax request:

  }else{ var me = this; $.ajax({ ... success: function(data){ description = data[0]; $(me).css('width', '70%'); 
+12
source

Just add this to your $.ajax ...

 context: this, 

... and it will work.


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

Source: https://habr.com/ru/post/921034/


All Articles