Utilize jQuery and ajax to insert an image into a div element

Would appreciate some guidance on adding an image to a div tag using jQuery and Ajax. I've been struggling to find a solution despite trying various methods.

The image I need is located in steel_agg_bof_flash_en.html, which can be accessed as an XML file. This file contains the data interfaces information required for this task.

Currently, I am working on localhost, and the file steel_agg_bof_flash_en.html is in my root folder.

<data>
  <labels>
    <closebtn><![CDATA[]]></closebtn>
    <path></path>
    <addbtn><![CDATA[add hotspots]]></addbtn>
    <deletebtn><![CDATA[delete hotspots]]></deletebtn>
    <resetbtn><![CDATA[reset hotspots]]></resetbtn>
  </labels>
  <basics>
    <lg></lg>
    <clickmapid>contentbean:9492</clickmapid>
    <adminMode>0</adminMode>
    <imgpath>/linkableblob/internet_en/9492/image/steel_agg_bof_flash_en-image.jpg</imgpath>
    <format>landscape</format>
    <title><![CDATA[]]></title>
  </basics>
  <hotspots>
    <hotspot>
      <hsid>clickMap_item_9510</hsid>
      <title><![CDATA[Optimal design ]]></title>
      <position><![CDATA[350,469,247]]></position>
    </hotspot>
 
    ....
  </hotspots>
</data>

This is the code I have at the moment, but unfortunately, it's not working as intended:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="" class="content_item">
  <h1>BOF vessel </h1>
  <!-- class should be either "portrait" or no class for "landscape" -->
  <div id="clickMap">
    <div id="clickMapFlashContainer"></div>
      
      <div id="clickMapFlash" style="width:auto"></div>
    </div>
    <div id="clickMap_item_default" class="clickMapItem text">
      <div><p>Due to long-standing contact with customers RHI has detailed knowledge of the requirements that steelworkers place on refractories. This is why RHI has been involved in the development of package and system solutions for many years und nowadays offers customized high-end solutions for basically all individual customer requirements.</p></div>
    </div>
</div>
    <script type="text/javascript">
        $( document ).ready(function() {
        $.ajax({
            type: "GET",
            url: "steel_agg_bof_flash_en.html",
            dataType: "xml",
            success: function xmlParser(xml) {

              $(xml).find('basics').each(function () {

                  var img = $(this).find('imgpath').text();

                  $('<img />')
                     .attr('src', "" + img + "")         // ADD IMAGE PROPERTIES.
                     .width('200px').height('200px')

                     .appendTo($('#clickMapFlash'));     // ADD THE IMAGE TO DIV.
                });
            }
        });
    });

    </script>

</body>

Answer №1

Consider updating the relative URL to an absolute one within the imgpath tag:

<imgpath>http://www.example.com/images/works.jpg</imgpath>

By using an absolute URL, you can ensure that the image is not being loaded from a non-existent location on your file system.

Your code appears to be functioning correctly:

https://jsfiddle.net/ae031p5q/

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

The React Context Value keeps coming back as undefined every time

As a beginner working with contexts, I am taking it slow. Recently, I came across logging Providers to test the value and encountered a constant 'undefined' result. To troubleshoot, I tried moving them side by side in the code to see if it makes ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

How to centrally align tabs in Material-UI AppBar using ReactJS

I'm developing a React Application using Material-UI and facing difficulty in centering the 3 tabs within the blue AppBar. Currently, they are aligned to the left like this: (unable to embed images at the moment, apologies) This is the code snippet ...

css - targeting the last child element using a type selector

I'm attempting to target the final child element of type <div> within the container "#myDiv" <div id="myDiv"> <div> <img> <div> <div>text</div> ...

When performing web scraping with Puppeteer, employing a single selector to target various types of data

As a budding web developer, I have recently delved into coding. My current knowledge is limited to HTML, CSS, JS, and NODE. Currently, I am working on a project involving page scraping and utilizing puppeteer. CHALLENGE - In scenarios like the o ...

"Unfortunately, the server encountered a 500 error while processing AJAX requests in

Hello everyone! I could really use some assistance. I am experiencing a minor issue where a new object should be created when a button is clicked, without the page reloading. Only one parameter is needed to create this object. The problem arises when clic ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

Error: Unrecognized error encountered while using Angularjs/Ionic: Property 'then' cannot be read as it is undefined

codes: js: angular.module('starter.services', ['ngResource']) .factory('GetMainMenu',['$http','$q','$cacheFactory',function($http,$q,$cacheFactory) { var methodStr = 'JSONP' ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

What is the best way to loop through an array in JavaScript, calling a prototype function recursively within itself?

I am currently working on developing a custom polyfill for the Array.flat() method. However, I have encountered some challenges when trying to call the function recursively within itself to flatten nested arrays further. It seems that when I write code wit ...

Adding emphasis to the text within a submit button using HTML and CSS

I am experimenting with styling an input submit button to resemble a regular hyperlink. Everything looks great using CSS, except for the fact that the underlining is not showing up. Here is my CSS: input.addemail { border: 0px; background-color: #1e ...

Login Form with Semantic UI Dropdown

I'm currently working on incorporating a dropdown login form for a website using the Semantic UI framework. However, I am facing an issue where the form is placed within an item on the menu, causing the dropdown menu to disappear once clicked. Here is ...

The DataTables plugin is failing to show the server response

I have been attempting to retrieve data from an API using AJAX Datatables. Although the data appears to be successfully retrieved and displayed in the network tab, it is not being rendered properly within the DataTable. Below is my AJAX Call: "ajax": { ...

Unable to locate CollapsiblePanelExtender using RegisterStartupScript results in returning null

I am currently working on a .NET 4 web page that incorporates a User Control featuring the following elements: <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server"> </asp:ScriptManagerProxy> <asp:LinkButton ID="btnExpand" runat=" ...

Ensuring my Mongo connection string is accurate for hosting a remote database with authorization

Having difficulty replicating the MongoDB connection in NodeJS using Mongojs. mongo --host dds-xxxx.mongodb.rds.aliyuncs.com:3717 -u root -p password --authenticationDatabase admin Here is my current code snippet: /* MongoDB setup */ // Define parameter ...

Preventing parent properties from overriding descendants is a key part of maintaining a hierarchical

I found a css file online that I'm using for a website I'm building, but I am only incorporating certain components from it. The issue is that the global styles in this css file are overriding all the global styles on my website. My solution was ...

Unique design Radio Button Inputs with Custom CSS Styling and Enhanced Accessibility for Voice Controls

On my website, I have implemented custom radio buttons using this model: The custom radio buttons are working well with various browsers and are accessible with Jaws. However, I encountered an issue when trying to use Voice Over as the radio button canno ...

Sending selected option from bootstrap dropdown to the subsequent php page

Is there a way to pass the selected value from a dropdown in Bootstrap to the next page? I have multiple options to choose from and I don't want to create separate pages with the same layout for each option. How can I pass the dropdown value to the ne ...

Should I avoid incorporating jQuery into Angular applications?

I'm curious about whether it's best to steer clear of using jQuery in an Angular application, considering the idea that only one entity should be handling DOM manipulation. Has anyone encountered situations where jQuery was the necessary quick fi ...

html / CSS Center image in div with primary image as background

I am encountering a unique issue that I haven't come across in my search so far. My objective is to create an HTML page where each background image div represents one page for clean printing. .thirdBackgroundPage { background-image: url("images/fir ...