Result in Ajax multiplying the array values

0

When making a query to the database, it generates a response that is received by the success function of ajax, but when I want to put $. each , it is not that I have a problem with that, no and no, the json is parsed, everything is fine, only that it generates more responses than the server gives, for example, a single message comes out and returns approximately 11.

success: function(response){

    $this = $(this).children(".messages");
    response = JSON.parse(response);

    $.each(response, function(){
      console.log(response);
      $('<div class="message-sent">' + response.message + '</div>').appendTo($this);
    })
  $this.append(response);
 }

As I put it above, first I make a console.log, the array appears with the same number of results that the answer delivers, but when sent by $ .each they multiply infinitely, that is. help

    
asked by Esteban Fernández 24.07.2018 в 02:41
source

2 answers

1

I do not know exactly what the constitution of your JSON is. The truth is that you apparently have a duplicity of append.

The cleanest thing is that inside the loop you concatenate the data in a variable, and then, outside the loop, you update the container or element with that information. Making an append each time within a loop is not recommended, since you modify the DOM in each iteration.

Here I simulated a JSON, to show a way of reading it, taking the key message of it, concatenated in the loop and then out of it we update the div whose id is response in the DOM.

You can apply this solution in your code. If it does not work, please share the structure of your JSON and clearly explain in which container you want to put the content you extract in each .

var response = '[{ "id" : "1", "message" : "message1" },
  { "id" : "2", "message" : "message2" },
  { "id" : "3", "message" : "message3" }]';
var json = JSON.parse(response);
var divResponse = $('#response');

var html = "";

$(json).each(function(i, val) {
  html += val.message+"<br />";
  console.log(val.message);
});
divResponse.append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="response"></div>
    
answered by 24.07.2018 / 03:41
source
1

Try changing the way you go through the answer for this

response.forEach( (element) => {
  console.log(element);
}) 

In addition to removing the response = JSON.parse(response);

Here I leave you an example code. I hope it helps you.

    
answered by 24.07.2018 в 03:26