The loop forEach in ajax is programmed to display only the final record

When making an AJAX request, only the last record from the loop is displayed. See the code snippet 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;

                   }
               });

This content is being sent into a div with the ID of 'table'.

Answer №1

This particular line of code

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

is actually overwriting the value of inf with each iteration of the loop. Consequently, by the time the loop finishes running, inf only contains the data from the final round.

To address this issue, it is recommended to initialize inf as an empty string prior to starting the loop:

var inf = "";

Then, within the loop, replace the aforementioned line of code with the following one, which will add to the existing string:

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

By doing this, you will gradually build upon the HTML string during each iteration of the loop, resulting in a collection of paragraphs that align with your objective.

Answer №2

It seems like the issue lies in your loop where the inf variable is being overwritten with each pass. To avoid this, consider concatenating to your string on every iteration:

var inf = '';
var json_x = data;
json_x.forEach(function(item){
  inf += '<p>'+ item['id'] +"</p>";
});

Answer №3

It seems like the issue lies in this particular line of code:

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

You are replacing the old value with the new one instead of appending it (which I assume is your intention). To resolve this, you can modify the code as follows:

let inf = ""; // It's recommended to use "let" over "var"

// Update the information in the callback:
inf += "<p>"+ item['id'] +"</p>";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

The equivalent of an event listener in event handling

Here is an example of how to set up event listeners: document.getElementById("A").addEventListener("change", function (e) { // do something when A changes }, false) document.getElementById("B").addEventListener("click ...

SQLite INTERVAL RANGE Display

pd.read_sql_query(''' SELECT date(payment_date), sum(amount) as total_date, avg(sum(amount)) over (order by date(payment_date) RANGE BETWEEN INTERVAL &apo ...

The Ajax request is successful only on the second attempt

After setting up a WP login form with AJAX, I've encountered an issue where it only works on the second attempt. Meaning, when a user enters their username and password, clicks submit, it doesn't work. But if they try again by clicking submit onc ...

Using the `ng-repeat` directive as an argument in a Javascript function

I am struggling to pass the ng-repeat element to a JavaScript function, but it's not working as expected. <tr ng-repeat="x in myArry"> <td><input type="text" value="{{x.firstname}}" id="{{x.firstname}}{{$index}}" onblu ...

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Clicking to fade in and out with jQuery on data attributes

I have structured my HTML code as follows: <div class="col-sm-8"> <img id="click-1" class="glasses one active" src="<?php bloginfo('template_directory'); ?>/assets/images/Statesman-Three.png"/> ...

Tips for optimizing AJAX content for Google indexing

As I begin the process of developing a public website that utilizes client-side rendering with AngularJS, I have come across information suggesting that dynamically generated content may not be properly indexed by Google. This raises concerns about the imp ...

Having trouble getting the generated component from Ionic v4 CLI to function properly

I'm currently facing a challenge while working with the latest version of Ionic. I am struggling to make a CLI-generated component work properly. After starting with a blank project, I create a new component using the following command: ionic genera ...

Exploring the front side of a cube using three.js

Exploring the following example: I am curious to know whether it's possible to determine which side of the cube is facing the camera, i.e., the front side. So far, I have been unable to figure this out. Any assistance on this matter would be greatly ...

Encountering a problem while parsing JSON in Ruby: Uncaught exception 399 - unexpected token detected!

Whenever I try to use JSON.parse(response['data']), Ruby throws an error: Uncaught exception: 399: unexpected token at ... I can't figure out why this is happening. In casperjs, I send the following data back to Ruby: this.echo('{"da ...

How can I extract a substring using jQuery?

<script type="text/javascript"> $(function(){ $("a[rel='tab']").click(function(e){ e.preventDefault(); pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $(&apos ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...

How can you calculate the total time difference on a group using the SUM() function in MySQL?

I have a dataset with results displayed as follows: SELECT User_ID, StartTime, EndTime, TIMEDIFF(EndTime, StartTime) AS TimeDiff FROM MyTable ------------------------------------------------------------------ | User_ID | StartTime | End ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

PHP - Real-time form validation?

Looking for advice on implementing real-time feedback for a registration form on my website. Is there a way to automatically notify users if their chosen username is already taken without requiring them to submit the form first? Thanks in advance. ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

Change a single-row array to a multi-row array

I currently have an array that is returning values in the following format: 0: 1,2,3,4 However, I would like it to return array values in a different way: 0: 1 1: 2 2: 3 3: 4 If I am using JavaScript, what is the best approach to accomplish this? ...

ExpressJs does not support query parameters with the router.get method

I am currently working on developing an Express app. Here is the code snippet I am using: const express = require("express"); const router = express.Router(); router.get("/:id", ControllerHandler(UserController.getSingle, GetUserReque ...

Encountering a 404 error while using Node.js for app.get requests with Postgres as the

Currently, I am in the process of learning Node.js by following a tutorial that guides me on building a simple API. The tutorial utilizes a sample database for demonstration purposes, but I decided to use my own Postgres DB instead. However, when trying to ...