Skip to content
Advertisement

ajax outputs only the last record from the loop forEach

ajax the request displays only the last record from the loop, the code below:

$.ajax({
                   method: "POST",
                   url: "{{asset('/num')}}",
                   dataType: "json",
                   success: function (data) {
                       var inf;
                       var json_x = data;
                       json_x.forEach(function(item){
                           inf = '<p>'+ item['id'] +"</p>";
                       });
                       insTabl = document.getElementById('table');
                       insTabl.innerHTML = inf;

                   }
               });

sending in div id='table'

Advertisement

Answer

This line

inf = '<p>'+ item['id'] +"</p>";

is overwriting the value of inf each time through the loop. As a result, when the loop is over, inf simply holds the corresponding value from the last iteration.

To fix it, initialise inf as an empty string, before the loop:

var inf = "";

and then replace the line above, inside the loop, with this one, which appends to the string:

inf += '<p>'+ item['id'] +"</p>";

That way, you make the HTML string longer each time through the loop, and end up with the series of paragraphs that I assume you want.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement