Tips for transforming a JSON array of file paths for images hosted on a server into a JavaScript array for showcasing them. Leveraging the power of AJAX

I am looking for a way to use HTML file/ajax code to extract the JSON message and store the PATHS as a JavaScript array. This will allow my buildImage function to display the first image in the array. I am new to AJAX and suspect that my issue lies in converting the JSON to JavaScript. Also, I am unsure whether my code generates a JSON array or object. Should I consider downloading a library to help me understand JSON better?

Below is a PHP file that loads the paths of the images. It seems like json_encode is converting the PHP Array into a JSON message.

<?php
include("mysqlconnect.php");

$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());   


$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}

echo $images = json_encode($data);
?>

Below is the script that will be loaded on a Cordova app.

<!DOCTYPE html>
<html>
<head>

<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="css/cascading.css">

    <script>



    function importJson(str) {
       // console.log(typeof xmlhttp.responseText);

        if (str=="") {
            document.getElementById("content").innerHTML="";
            return;

        }
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();

        } else { // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

        }



        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4) {

                //var images = JSON.parse(xmlhttp.responseText);

                document.getElementById("content").innerHTML=xmlhttp.responseText;


            }

        }

        xmlhttp.open("GET","http://server/content.php");
        xmlhttp.send();



    }



  function buildImage(src) {
        var img = document.createElement('img')
        img.src = src
        alert("1");
        document.getElementById('content').appendChild(img);
    }

    for (var i = 0; i < images.length; i++) {
        buildImage(images[i]);
    }



    </script>

</head>

<body onload= "importJson();">

        <div class="contents" id="content" ></div>
        <img src="img/logo.png" height="10px" width="10px" onload= "buildImage();">
</body>

Answer №1

Let's clear up some confusion here: JSON is a valuable string format that can be converted into a JavaScript object, array, or primitive value. There is no entity known as a "JSON object."

If you check the type of xmlhttp.responseText with:

console.log(typeof xmlhttp.responseText);

You'll find that it is indeed a string.

To transform it into an object (such as an array), simply parse it like this:

var arrayOfData = JSON.parse(xmlhttp.responseText);

You can then verify that it is now an array by using:

console.log(arrayOfData);

Next, to iterate through the array, you can use a function like this:

function displayImage(src) {
  var image = document.createElement('img')
  image.src = src
  document.getElementById('content').appendChild(image);
}

for (var index = 0; index < arrayOfData.length; index++) {
  displayImage(arrayOfData[index]);
}

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

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

What is the best approach to manage various json data specific to each jquery tab?

Within my webpage, I am utilizing three different (jQuery) tabs: Overview Pricing Destination info Each of these tabs houses completely unique sets of data. By specifying a URL in the href attribute, I can trigger an AJAX call to retrieve this data. How ...

Ways to modify the source of images that do not possess a class or ID using JavaScript

I'm struggling to change the source of the img element using JavaScript and Ajax. The img tag doesn't have any IDs or classes, making it difficult for me to select and update the src. Can anyone provide guidance on how I can accomplish this? Belo ...

Using regular JavaScript with code inside ng-view in AngularJS involves incorporating event listeners and manipulations that can interact

Just delving into the world of angularJS for the first time. I've set up the routing service, which involves having a div with routing that calls in a template containing HTML code. I also have a range of regular JavaScript functions necessary for the ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

Transform LINQ output into a JSON format

I am currently working on an ASP.NET webservice project where I connect to a Database using Entity framework connection. I am trying to return a JSON output in the following format: [{"DIM_FECHA":[201502,201503,201504]}{"FCT_TOTALFACT":[1234567,1234555,1 ...

What might be causing the Delphi 2007 ASP.NET AJAX request to return [object Object]?

Is there anyone here who has successfully utilized the AJAX-enabled ASP.NET Web Application wizard in Delphi 2007 to make ajax calls? If so, what's the key to making it function properly? I am asking for two reasons. First, my attempts have not yield ...

Retrieve information from the pouchdb database

After successfully storing data in PouchDB, I'm wondering how to retrieve this information and display it in HTML using AngularJS. var db = new PouchDB('infoDB'); function getData(){ $.getJSON('test.json', function(data) { ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

Backing up a mongodb collection can be easily achieved with the help of express.js and Node.js

I am looking to create a monthly backup of my userdatas collection. The backup process involves: I intend to transfer the data from the userdatas collection to a designated backupuserdatas collection. A batch program should be scheduled to run automatica ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

AWS Cognito - ECS Task Fails to Start

I'm facing an issue with using JavaScript to execute a task in ECS Fargate. AWS suggested utilizing Cognito Identity Credentials for this task. However, when I provide the IdentityPoolId as shown below: const aws = require("aws-sdk"); aws.co ...

Implementing a play and pause button functionality for the carousel in Bootstrap 5

How can I implement a play/pause feature on the same button when clicking in a Bootstrap 5 carousel using jQuery? **HTML ** <div id="customSlider" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2500& ...

How to Shift Focus to a Component in Vue.js

Within a container, I have a form section enclosed by a component that remains hidden due to the use of v-if. Upon clicking a button, the boolean value is toggled, revealing the previously concealed component. At this point, I aim to shift focus to the ini ...

The custom validation process encountered an error: callback is not a valid function

Encountering an issue with a custom validator in node.js while using mongoose. The goal is to verify if a query already exists in the headerLog before attempting to insert it. Take a look at the code snippet below: var mongoose = require('mongoose& ...

Having trouble concealing the logout button even after signing out with ng-show in angularjs

The code for displaying the logout button is as follows: <li class="dropdown" data-ng-if="userName"> <a href class="dropdown-toggle clear" data-toggle="dropdown" data-ng-show="userName"> </a> <!-- dropdown --> <u ...

Utilize a single function to toggle the visibility of passwords for multiple fields upon clicking

Is there a way to optimize the function used to hide passwords for multiple fields when clicked? Instead of having separate functions for each field, I would like to have one function that is only active on the clicked button. For example, if the toggle ...

"Selecting elements using the nth-of-type CSS selector alongside other

Dealing with a grid layout that includes spacers between certain items, I attempted to use the :nth-of-type selector in CSS to style only the first column of items and not apply those styles to the right side. However, it seems that the CSS gets confused w ...