views:

80

answers:

3

Hi there

I am trying to append my JSON data to a div. For some reason I am not seeing, it does not append. The data is collected correctly from Django view, I can see this is the FireBug console.

Here is my JS

$.getJSON('/chat/xhr_test/', function(response_array) {
  var arr = response_array;
       $.each(arr, function(count, item) {
  var messageList = (this.pk + ' ' +this.nickname +': '+ this.message +'<br>');
  $("#chatbox").append(messageList);
  });
 });
A: 

You can't use "this" when you have function variables in your each statement. remove count and item, then you can use "this" or rather use item[count]

var messageList = (item[count].pk + ' ' +item[count].nickname +': '+ item[count].message +'<br>');
Mohamed
hi there, thanks!this does not make any difference, it still does not append the div #chatbox. Even if i out static text in the append("This is text") is does not append it. And it should then?
Harry
A: 

Let's debug

$.getJSON('/chat/xhr_test/', function(response_array) {
  var arr = response_array;
  console.dir(arr);//is this an array?
  var chatbox=$('#chatbox');//cache the chatbox -- ideally this should be placed outside getJSON for reuse
  console.log('chatbox length', chatbox.length);//does chatbox exist?
  if (chatbox.length){
    $.each(arr, function(count, item) {
        console.log(count, item);//getting an integer and an object?
        var messageList = (item.pk + ' ' +item.nickname +': '+ item.message +'<br />');
        console.log(messageList);//look good?
        chatbox.append(messageList);//append to the cached chatbox element
     });
    });
  }
});

Once you make sure your variables are set up the way you think they are, things fall into place.

czarchaic
A: 

$.each might require you to specify .items instead of passing the whole variable:

$.each(arr.items, function(count, item) {
T. Stone