Trouble with loading images using AJAX in ASP MVC core 3.0

After successfully fetching data from the API controller using an AJAX request, all the data is loaded correctly, including the image source. However, I have encountered an issue where the controller name is being appended to the image source, resulting in a broken link. Below is the code snippet for the AJAX request:

$.ajax({
    type: 'GET',
    url: '/api/PieData',
    dataType: 'json',
    success: function (jsonData) {
         if (jsonData == null) {
              alert('no data returned');
              return;
          }

          $.each(jsonData, function (index, pie) {
             var pieSummaryString = '<div class="col-lg-4 col-sm-6 mb-4"> ' +
                        '  <div class="card h-100" style="width: 17rem;">' +
                        '     <img class="card-img-top" src=' + pie.imageThumbnailUrl + ' alt="Image Not Found">' +
                        '      <div class="card-body">' +
                        '         <h3 class="card-title">' + pie.price + '</h3>' +
                        '         <h3>' +
                        '             <a href=/Pie/Details/' + pie.pieId + '>' + pie.name + '</a>' +
                        '         </h3>' +
                        '         <p class="card-text">' + pie.shortDescription + '</p>' +
                        '    </div>' +
                        '    <div class="addToCart">' +
                        '        <p class="button">' +
                        '             <a class="btn btn-primary" href=/ShoppingCart/AddToShoppingCart?pieId=' + pie.pieId + '>Add to cart</a>' +
                        '         </p>' +
                        '     </div>' +
                        '  </div>' +
                        '</div>';
                    $('#pieDiv').append(pieSummaryString);
                });
            },
            error: function (ex) {
                alert(ex);
            }
        });

The database returns the source as "Images/PieImages/applepiesmall.jpg", but when displayed on the page, it becomes https://localhost:44365/Pie/Images/PieImages/applepiesmall.jpg. The addition of "Pie" to the source seems puzzling. The JSON returned by the API is as follows:

{"pieId":1,"name":"Apple Pie","shortDescription":"Our famous apple pies!","price":12.95,"imageThumbnailUrl":"Images/PieImages/applepiesmall.jpg"}

Answer №1

One of the main reasons why 'Pie' needs to be added to your image URL is due to the absence of a forward slash in the JSON image path.

"imageThumbnailUrl":"Images/PieImages/applepiesmall.jpg"

should instead be

"imageThumbnailUrl":"/Images/PieImages/applepiesmall.jpg"

The inclusion of / before Images indicates that the image path should start from the root directory of the website. Without this initial /, the image path will be calculated from the current web directory, such as your pie controller.

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

What could be the reason why my AJAX error is not displaying the exception from my Webmethod?

I am currently utilizing Google Chrome for my work tasks. After referring to , I attempted to throw an exception from a webmethod. However, no output is shown in the console.log. The only information I received is a generic error message from the network ...

Is it possible to only show the div element in my AJAX request without displaying the entire page

Is it possible to only show a specific div in my ajax request without displaying the entire page? The entire page is loaded, but I only want to display one div and hide the header and footer. However, I still need the header to be present on the page. jQ ...

Extracting content from a concealed frame and displaying it on a visible frame via javascript

Is there a method to extract a specific DIV element from an HTML frame and display it in a visible frame using JavaScript? For instance, if I create a hidden frame containing Google search results, is there a way to show only the search results on the vis ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

The controller did not have any corresponding action to fulfill the request sent from AngularJS connecting to Asp.Net WebApi

My mind is spinning. I am diving into the world of learning AnjularJS with Asp.Net Web Api. The following code snippet features an AnjularJS controller with an ajax call to a Web Api service. CustomerController = function ($http, $scope, $httpParamSeriali ...

Discover the solution for consistently passing solely the first row data when submitting the bootstrap form modal submit button

I'm facing an issue with the Bootstrap edit form Model where it only passes the data from the first row to every other row. How can I resolve this problem? In my table view, I have a list of records and each row has two buttons: 1. Done and 2. View. ...

Saving, displaying, and removing a JSON document

As someone new to the world of JavaScript, I am encountering an issue with JavaScript and AJAX. I am aiming to create a function that allows me to add new elements with unique indexes. After saving this information to a JSON file, I want to display it on a ...

How can I transfer a variable from jQuery to PHP using AJAX?

I am currently working on a form that utilizes PHP to send email notifications for inquiries. Additionally, I have implemented jQuery to automatically populate details into a specific div. Could someone guide me on how to pass the jQuery variable to PHP t ...

Introducing an exception to every jQuery post() method

Our app utilizes AJAX with jQuery to manage user information. We determine the success or failure of an API call by checking data.success or data.error respectively. Additionally, we implement the jQuery error() function in each post() method to handle any ...

Send PHP data through AJAX and retrieve it on a different PHP page

I need to send a variable through an AJAX URL to another PHP page and retrieve it using: $id=$_GET['id']; Here's an example where the value is passed, for instance $id=6. <a id="pageid" href="ifsc-bank.php?id=<?=$id?>"><im ...

"422 (Unprocessable Entity) Error When Submitting a Form in Rails Application

I recently delved into the world of ruby on rails a few days back. My current challenge involves transferring data from html tags to a ruby function using ajax. Below is the error message that has been giving me trouble: POST http://localhost:3000/ajax/o ...

Having trouble invoking the controller method through an Ajax request

Controller: [HttpDelete] public void RemoveState(string id) { int stateId = Convert.ToInt32(id); var db = new ClubDataContext(); var stateInfo = from record in db.StateInfos where record.S_ID == stateId select record; ...

Ways to execute a php script or function when an html button is clicked

I've searched high and low on the internet, including asking this question on stackoverflow, but I'm struggling to grasp new concepts as a newbie. Please go easy on me. My goal is to trigger a php script or function with a button click while usi ...

Troubleshooting a recurring ajax problem with jQuery inside a pop-up dialog box

I am experiencing a peculiar problem and I could really use some help in figuring out where I am going wrong. Within my code, I have a div named "popup" and a button labeled "send_mail". Here's the scenario: when the "send_mail" button is activated, ...

The JSON data in CRM 2011 is displaying as undefined, but the URL is still showing the

I have been struggling with a simple odata query where the call is successful, but I keep getting undefined results. I've tried various methods to inspect the object, but it still shows undefined. What could be causing this issue? UPDATE: After some ...

Scrolling to an id within dynamically loaded content using jQuery after an ajax request

After loading content via ajax, I am unable to scroll to the item, as the page remains at the top. Strangely, when I refresh the page dynamically with content caching enabled, the page scrolls to the desired target. var startPageLoader = function( pid, si ...

I'm having trouble with my dataTable creation using JQuery. Can anyone help me troubleshoot?

I've attempted various methods to make this work. Here's what I'm importing: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script type="text/javascript" src="https://cdn.datatabl ...

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

How to retrieve XML data using jQuery AJAX

I am facing an issue with returning an xml file from the server to the client and parsing it using jQuery's ajax function. The code snippet is as follows: Client: $("#submit").click(function(){ $.ajax({ type: "POST", ...