0

This page of my app is a dashboard which consists of div's acting as 'panels', like so

<div class='panel' id='usersPanel' data-request='users'>
    <h1>Users</h1>
    <p class='panel-contents'>Will be filled with AJAX results</p>
</div>

On page load, they're populated via AJAX

$(document).ready(function() {
    $('.panel').each(function(index, value) {
        $.get('/panel', {'content': $(this).attr('data-request')}, function(data) {
            $(this).find('.panel-contents').html(data);
        });
    });
});

The request is sent fine. The response is OK. But I can't seem to write it into .panel-contents. Am I missing something?

starleaf1
  • 2,701
  • 6
  • 37
  • 66

2 Answers2

3

I believe the problem is in your success function. When that executes this equates to something different try:

$(document).ready(function() {
    $('.panel').each(function(index, value) {
        var panel = this;
        $.get('/panel', {'content': $(this).attr('data-request')}, function(data) {
            $(panel).find('.panel-contents').html(data);
        });
    });
});
MikeS
  • 1,734
  • 1
  • 9
  • 13
  • He said the response was okay. He just cannot replace the html. – Andrew Ice Jan 23 '17 at 16:03
  • 1
    Yes, and I believe he can't replace the html because 'this' within the success function is not the same thing as the 'this' within the success function. The scope is different. – MikeS Jan 23 '17 at 16:04
2

You won't get this inside the $.get success listener - cache this beforehand like below:

$(document).ready(function() {
    $('.panel').each(function(index, value) {
        var $this = $(this);
        $.get('/panel', {'content': $(this).attr('data-request')}, function(data) {
            $this.find('.panel-contents').html(data);
        });
    });
});
kukkuz
  • 41,512
  • 6
  • 59
  • 95