I’m using an $.ajax();
request to make a call to my controller. Inside the console.log();
, it’s correctly displaying all of the data coming in but when I try to display it on the browser via $('#displayCoins').text(item.oldCoins);
– only the very last piece of data if being displayed instead of all of the data.
What am I doing wrong and how can I go about rectifying this in terms of displaying all of the data on the browser?
$.ajax({ type: "GET", url: '/my/endpoint', dataType: "html", success: function (response) { var resp = response; var respParsed = $.parseJSON(resp); $.each(respParsed, function(i, item) { console.log(item.oldCoins); $('#displayCoins').text(item.oldCoins); }); } });
Advertisement
Answer
The problem that you are having is you are REPLACING the text every time through the loop instead of appending it.
One solution is to append the data to an array, then output it to the DOM via a single join.
$.ajax({ type: "GET", url: '/my/endpoint', dataType: "html", success: function (response) { var resp = response; var respParsed = $.parseJSON(resp); oldCoins = []; $.each(respParsed, function(i, item) { console.log(item.oldCoins); oldCoins.push(item.oldCoins); }); $('#displayCoins').text(oldCoins.join("n")); } });