Displaying Various Photos within bootstrap-table using Ajax Response

Upon receiving a response from an AJAX call, my task is to create a bootstrap-table with the data. The response contains an array with information about images, such as their paths and names. However, when trying to populate the bootstrap-table with this data, only a single image is displayed instead of all the images in the array.

Here is my function and AJAX call:

function printCatchTable(){
var $table = $('#TableLastCaught');

$.ajax({
type: "GET",
url: '/api/lastcaught',
success: function(response) {

for(var i =0;i < response.length ;i++){
var item = response[i];
var picinfos = item.picinfos;

for(var x in picinfos){
var filename = picinfos[x].filename;
}

faengeTableData.push({
_id: item._id,
date: item.datum,
time: item.uhrzeit,
pics: filename,
}

$table.bootstrapTable({data: faengeTableData});
$table.bootstrapTable('togglePagination');
}   
})
} 

function imageFormatter(value, row) {
    return '<img src="files/'+value+'" />';
    }

This is the data received:

{
   "_id":"5c81253a4a582827f09969a7",
   "date":"2019-03-07",
   "time":"10:11",
   "picinfos":[
      {
         "filepath":"/files/1551967546627.jpg",
         "mimetype":"image/jpeg",
         "filename":"1551967546627.jpg",
         "size":322289,
         "metadata":{
            "GPSLat":"",
            "GPSLon":"",
            "CreateDate":"",
            "CreateTime":""
         }
      },
      {
         "filepath":"/files/1551967546634.jpg",
         "mimetype":"image/jpeg",
         "filename":"1551967546634.jpg",
         "size":275692,
         "metadata":{
            "GPSLat":"",
            "GPSLon":"",
            "CreateDate":"",
            "CreateTime":""
         }
      },
      {
         "filepath":"/files/1551967546638.jpg",
         "mimetype":"image/jpeg",
         "filename":"1551967546638.jpg",
         "size":261305,
         "metadata":{
            "GPSLat":"",
            "GPSLon":"",
            "CreateDate":"",
            "CreateTime":""
         }
      }
   ],
   "userid":"5c09116a4e2d1f1cc9d48d6a",
   "__v":0
}

Currently, only one picture is displayed under the "Pics" column:

<th data-field="bilder" data-sortable="false" data-formatter="imageFormatter">Pics</th>

<tr id="5c8a196cc7b15419d5755153" data-index="1">
<td style="">2019-03-14</td>
<td style="">6:15:19</td>
<td style=""><img src="files/1552554348794.jpg"></td>
</tr>

If I don't use the formatter, I see:

<tr id="5c8a196cc7b15419d5755153" data-index="1">
<td style="">2019-03-14</td><td style="">6:15:19</td>
<td style="">1552554348794.jpg</td>
</tr>

The question remains: how can I display all the images in the table column/row and have the imageFormatter construct the image source string?

Answer №1

for(let x in picinfos){
    let filename = picinfos[x].filename;
}

Instead of replacing the filename in each iteration of the for loop, you should store the filenames in an array and then pass it to the table.

for(let x=0; x < res.length; x++){
  let item = res[x]
  let picInfos = item.picinfos
  let fileNames = []

  for(let i=0; i < picInfos.length; i++){
    fileNames.push(picInfos[i].filename)
  }

   //rest
 }

Answer №2

My conclusion is:

function displayCatchTable(){
    var $table = $('#TableLastCaught');

    $.ajax({
        type: "GET",
        url: '/api/lastcaught',
        success: function(response) {

            var catchTableData = [];

            for(var i =0;i < response.length ;i++){
                var item = response[i];

                var picinfos = item.picinfos;
                var fileNames = [];

                for(var k=0; k < picinfos.length; k++){
                    var filestring = formatImage(picinfos[k].filename);
                    fileNames.push(filestring);
                }

                catchTableData.push({
                    _id: item._id,
                    date: item.datum,
                    time: item.uhrzeit,
                    pics: fileNames,        
                });
            }

            $table.bootstrapTable({data: catchTableData});
            $table.bootstrapTable('togglePagination');

        }   
    })
}

function formatImage(value) {
    return '<img src="files/'+value+'">';
}

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

Identify the page search function to reveal hidden content in a collapsible section

Our team has implemented an expandable box feature on our wiki (in Confluence) to condense information, using the standard display:none/block method. However, I am looking for a way to make this work seamlessly with the browser's find functionality. S ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

Retrieve selected value from HTML input with datalist and use it as an argument in a method

I have a datalist in my HTML input where I need to pass the selected value into JavaScript / Angular. It must be passed because the datalist is being used in an HTML table with multiple entries. Most examples I've come across show how to grab the valu ...

Failure of Angular to execute HTTP calls asynchronously

I am feeling a bit perplexed about how and when to use the .then and/or .success functions. Here is a function example: $scope.handleData = function(option){ if(option == 1){ link = firstLink/; }else{ link = secondLink/; } ...

ASP.NET page experiences issues with executing Javascript or jQuery code

Having trouble with client scripts not functioning correctly on a child page that utilizes a master page. Looking for help to resolve this issue. <%@ Page Title="" Language="C#" MasterPageFile="~/Store.Master" AutoEventWireup="true" CodeBehind="NewSt ...

JavaScript, PHP handlers, and CommentBox all work together seamlessly to create

$("#login").click(function(){ $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){ console.log(data); //retrieves data from login box and sends it to the handler, returning a JSON array }); template = $("#hid ...

Sorting a datatable in JSF 2 using Ajax when a select list item is selected and a button is clicked

I am trying to implement AJAX functionality in a data table where the data changes and filters based on the selected state from a drop down menu. Here is my current setup: <p>Choose State to Filter By:</p> <h:selec ...

Check the status of the audio source URL using JavaScript

I am currently live streaming audio to my player using the Soundcloud API. <audio></aidio> <source src="soundcloud-track-url"></source> Within my code, I have added an onerror eventListener for both the <audio> and <sourc ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

The loader image does not appear on mobile screens during an AJAX call, but it functions correctly on desktop screens

While I have successfully implemented a loader (.gif) using a div tag in an AJAX call for desktop screens, the same code is not functioning properly on mobile devices. Instead of displaying the loading animation, it simply shows a white screen. <div ...

Converting Ajax Request Headers from UTF-8 to ISO Character Set

I am encountering an issue with character encoding on my web page. The page is encoded in iso-8959-9, but when I send ajax requests to the same page to save data to the database, the characters are converted to utf-8. Although my response header shows the ...

Error: Javascript unable to generate video thumbnail using ffmpeg

I'm having trouble generating a thumbnail from a video file using JavaScript. I keep encountering the error below: ChildProcessError: `/workspace/node_modules/@ffmpeg-installer/linux-x64/ffmpeg -ss 0 -i valid-video-link -f image2 -vframes 1 -vf scale= ...

Sorting a list based on user-defined criteria in Ionic 3

Currently working on a project using Ionic and Firebase, I am faced with the task of comparing arrays produced by users with those stored in Firebase. This comparison is essential for filtering a list of products. The user can reorder a list containing 3 ...

Create a React Native layout with a set width and the ability to stretch to fill

Is there a way to achieve this layout in react-native? I am looking to have a component with a fixed width on the right side, while another component on the left side takes up the remaining space. https://i.sstatic.net/3c6q6.png ...

Steps to display JSONP response delivered by PHP on a web page

I've written a JSONP script as shown below: <script> $(document).ready(function(){ $("#LoginForm").submit(function(){ var data = $(this).serialize(); //alert(data); $.ajax({ type:"POST", dataType:"jsonp ...

Tips for obtaining the current date in the head of a Next.js application

My goal is to utilize Date.now() within a script tag inside the head section. The code snippet I am using is as follows:- import Link from "next/link"; import Head from "next/head"; export default function IndexPage() { return ( ...

Encountering a 403 error message while using cljs-ajax for

I have a situation with my client-side code where I am utilizing cljs-ajax for POST requests. (defn persist-state [] (POST "/save" {:params {:state @state})) On the server-side, I have implemented compojure to handle the POST requests. (POST "/save" r ...

Concentrating on div elements using React

Can the focus() method be used to focus on a div element or any other elements? I have added a tabIndex attribute to a div element: <div ref="dropdown" tabIndex="1"></div> When I click on it, I can see that it gets focused. However, I am att ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

Creating a sliding menu using React and Headless UI (with Tailwind CSS)

Currently, I'm in the process of developing a slide-over navigation bar or slide menu that features panels opening on top of each other (I'm still searching for the most accurate way to describe it). The main concept revolves around having a sli ...