Showing an image using Javascript and Ajax

After using ajax to load data and attempting to display an image with javascript, I am encountering a problem where the image is not showing up. I could use some assistance in figuring out what mistake I made.

URL="testurl";
function getdata() {
    let xhr = new XMLHttpRequest();
    let image = document.getElementById("image");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
            var data = JSON.parse(xhr.responseText);
             var img = data.image;
              image.innerHTML += '<img src="' + img + '">';
}

    xhr.open('GET', URL);
    xhr.send();
}

Despite seeing the image loaded message in console.log(data.image); it seems like the image just refuses to appear on the screen.

image.innerHTML += '<img src="' + img + '">';

Answer №1

image.src = data.image;

Setting the source URL of an image should be done using the .src property, not the .innerHTML.

If image does not refer to an <img> tag, it would be best to rework the HTML so that it does. It is more efficient to directly manipulate properties in DOM objects rather than adding innerHTML that needs to be parsed. Keep coding!

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

Replace the anchor tags with a JavaScript array

Looking to replace a simple anchor link with JavaScript array code. We're taking the long route here, and it's not as straightforward as we thought. The scrollTo property isn't working for us; can anyone spot where we might be going wrong? ...

Implementing a long press feature for a stopwatch in React

I'm facing a dilemma with this particular issue. Before reaching out here, I scoured the community and found numerous solutions for handling long press events in React, but they all seem to focus on click button events. Currently, I am devising a sto ...

Showing text instantly upon clicking a radio button, in real-time

I'm working with a set of radio buttons that are linked to numbers ranging from 1 to 24. I need to show the selected number in another part of the page when a radio button is clicked. What would be the best way to achieve this? ...

Maintain Ajax content even when the back button is pressed

Currently, I am facing an issue with my product page that has infinite scroll pagination and loads more products using Ajax. For example, the URL is: domain/books. When a user clicks on a product, they are directed to the specific product page at: domain ...

Is there a way to transform this Json array into a format that JQuery can interpret easily?

Having a bit of trouble with this issue. I'm not entirely sure how to get it working correctly. According to Firebug, the Json object (or possibly array) from my ajax request appears as follows: { "jsonResult": "[ {\"OrderInList\":1}, ...

Button click does not trigger Ajax function

I've been staring at this all morning and I just can't seem to locate the source of the problem... This code involves javascript/ajax $('#subscribe').live('click', function(){ rel = $(this).attr("rel"); datas ...

How can I transform this to an ES6 module in JavaScript?

Currently, I am dissecting the ShaderGlow example found on this GitHub link in order to integrate it into my node application. The original author utilized <script> tags within the HTML document, while my entire application is structured within app. ...

Sending selected value from Mat-Select to header during API Call: A step-by-step guide

I'm dealing with an API that requires the country code in the header along with an authorization token and Bearer. In my component file, I am able to fetch the value from a mat-select dropdown. However, the setting for the API header and token is done ...

Displaying the state value within the input field using React Redux results in the value being unable to be altered

I am currently working on a Web Application that utilizes React and Redux. While I am new to both technologies, I have encountered an issue when trying to use them together. Specifically, I am unable to change the value of an input field when setting it wi ...

showing the chosen item in a Bootstrap dropdown [limited to the first menu option and using the attr() method]

Is there a way to dynamically display the selected menu option using the bootstrap drop down? Initially, I was able to select the first menu option and apply it to the bootstrap drop-down button. However, I encountered an issue where I cannot change the ...

Send an identifier as part of the URL to an HTML page that is accessed through a different URL

I am working on a template that is accessed via the URL /add and it contains multiple registration pages developed using ReactJS. Within the add.html page, which is called by the URL /add, there is an image upload form also implemented in ReactJS. This for ...

fetch data through ajax

I have developed an AJAX script to load data dynamically. $("#submit").click(function(e){ e.preventDefault() var loading = "<img src='/images/loading.gif' alt='Loading...' />"; var scrolltop=$('#scrollbox' ...

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

Unable to update FB Login button to display "Logout" after user logs in to FB app

As a junior developer, I'm currently working on integrating Facebook login functionality into my React application following the quickstart guide provided by Facebook developers. However, I've encountered some issues with making the necessary mod ...

Create a new variable within a function using an Angular factory

I am working with an Angular factory that generates a function including a variable to select an array for a dropdown. While I have successfully set the variable from a user selection in a controller, I am facing difficulties getting this variable into the ...

Locating and updating a subdocument within an array in a mongoose schema

Here is the mongoose schema I created: The userId is a unique number that Okta generates for user profiles. var book_listSchema = new mongoose.Schema({ userId:{type: String, required: true}, first_name: { type: String, required: true}, last_name:{ type: ...

Tips for converting asynchronous function calls into synchronous functions in Node.js or JavaScript?

Imagine you are managing a library that provides access to a function called getData. Users utilize this function to retrieve real data: var output = getData(); In the background, the data is stored in a file, so you have implemented the getData functi ...

Is there a way to retrieve the attribute value from a nested object without resorting to the standard JavaScript object traversal method?

Is there a way to automatically iterate through all the "value" attributes in the given object without explicitly mentioning "tags.value" or "style.value"? [ { "title": "Old Man's War", "author": { "n ...

Implementing a powerful multi-role authorization system in React

I am currently developing an application with multiple user roles (admin, user, manager). I am trying to restrict access to the admin route from both managers and general users, and also render the UI based on the user's role. I have attempted this bu ...

javascript for accessing JSON data both forwards and backwards

I am attempting to implement Next/Previous buttons for a json array, but I am encountering difficulties in making it work. Here is my latest attempt: <div id="text"></div> <button name="prev">go to previous div</button> <but ...