Unexpected symbols appearing in image tag after AJAX response

I'm currently grappling with an issue related to an AJAX request I am working on (I am quite new to the world of AJAX). I have set up an API and my goal is to fetch a PNG image using an Authorization header that requires a token supplied by me (which is stored in local storage). For instance, if I wanted to access the image with the Auth header, I would execute this code...

$.ajaxSetup({headers: {"Authorization" : localStorage.token}});

I can successfully retrieve the image. It shows up in the "Network" tab in Chrome, but when I try to display it on my div using the following code snippet...

$.ajax({
    //Utilize commas for multiple parameters
    type: 'GET',
    url: *image URL*,
    contentType: 'image/png',
    success: function (data) {
    binary = data;
    $("#image").attr("src", 'data:image/png;base64,'+ data);
}

...it appears in a strange character format (as shown below):

div id="image" src="data:image/png;base64, PNG

IHDRww^ÀþIDATxÚìÝ|ÔWº?þ½¿ÿ½Ý.ÅâÉd2îdâ®BB ÁÝÝ )îÞbÅÝ¥TÐzi)Ô ÞRÙn»rï]»+w·{þçùÌ<Ãd]ùýV¾çõz¿H&I°Ï÷ç<çï}OÊø;æO1ªzhÔÀdÆþKȤ!......." etc

I am looking to receive it back as either an image or a base64 string which I can directly insert into the src parameter. Despite extensive online research, I have not been able to find a solution yet.

Any insights or suggestions are highly appreciated.

Here is the response I am getting

Answer №1

Your website is retrieving the image data, which is stored in binary form.

To properly showcase the image on your site, you must convert the binary data to base64 encoding. Utilize the btoa function as outlined in this solution:

Answer №2

It appears that the image file you are receiving is in binary data format rather than the expected base64 format for insertion into the src attribute of the img tag.

If you have the image URL, you can simply place it directly in the img src without requiring an AJAX call.

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 is the best way to create a number input field that also accepts text input?

The goal I have in mind is to create an input field that will contain text like "100%", "54vh", or "32px". I am attempting to utilize the number input's up and down arrows, while still allowing the user to edit the text. However, it should only allow ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

Tips for redirecting to the index page instead of the login form after pressing the back button on the navigation

Hey everyone! I've been struggling with a problem for the past 4 hours and could really use some help. After logging in, the page redirects to a certain page, but when I press the back button in my browser, I want it to redirect back to that specific ...

Issue - The 'defaultValue' is failing to load the state value, and the 'value' is not being updated when changed

My current setup involves an input field in my MovieInput.tsx file: <input id="inputMovieTitle" type="text" onChange={ e => titleHandleChange(e) } value={ getTitle() }> </input> This is how the titleHandleChange function ...

Struggling to synchronize the newly updated Products List array in zustand?

Let me clarify the scenario I am dealing with so you can grasp it better. I have a Cart and various Products. When a user adds the product (product_id = 1) twice to the cart with the same options (red, xl), I increase the quantity of that item. However, i ...

Positioning elements in CSS using percentages allows for flexible and responsive

I am new to web design and I am trying to create a webpage similar to the one shown in this image. However, I want to set the height and width of the divs using percentage values instead of pixels. Whenever I attempt this, the boxes end up overlapping or ...

Is there a way to remove the ring shadow in TailwindCSS?

Here is a visual representation of the issue I'm facing (refer to the image): Check out the Image After inspecting with Chrome, it seems like the problem is connected to --tw-ring-shadow. I attempted to use classes like ring-0 and ring-offset-0 (men ...

The curly braces in AngularJS are not resolving as expected, however, the ng-bind directive is functioning properly

I'm currently working on a Django application and utilizing AngularJS for my frontend. I have a straightforward piece of code that looks like this: <div class="vert-carousel" ng-controller="PrizeController"> <div class="gallery-cell" n ...

JavaScript and HTML with Node.js

Exploring the world of HTML, running smoothly with a static IP address 192.168.56.152 using apache on the host computer. <!DOCTYPE html> <html > <head> <title>OnlinePage</title> <meta charset="utf-8"& ...

Having trouble with blueprintjs icons not appearing as they should on certain pages

I have recently updated an older React application from blueprintjs version 1 to version 4 by following the documentation. However, I am now facing an issue where the icons are not displaying correctly as shown in the image below. Could someone please poi ...

Use the slide bar to adjust the Angular filter value

I am diving into my very first AngularJS project and I must admit, I have zero experience with Angular. On my HTML page, I have implemented a slider bar with two handles to set a minimum and maximum value. Here is the snippet of code where this functionali ...

Centering divs using iPad media queries does not seem to work properly

While working on my website, I encountered an issue with displaying content properly on various mobile devices. I have implemented media queries for this purpose. Currently, on the main site, two divs (#wrap and #scrollbar) are positioned next to each oth ...

How to Generate HTML Reports Using JBoss?

Is there a convenient and efficient way to generate .html reports for JBoss applications that is not time-consuming? I have a database containing entities that I need to display in multiple tables. The report should include links to navigate between secti ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

How can I insert an HTML/PHP code snippet into a <ul> list using JavaScript?

My upload.php file saves images into an uploads/ folder within my main directory. I am looking to dynamically add a new li tag to my index file each time an image successfully uploads. Here is a snippet from index.php: <ul> <li><im ...

What is the best way to get both the id and name of a selected item in Angular?

Within my select field, data is dynamically populated based on names. My objective is to not only capture the selected name but also its corresponding ID. Here's a snippet of my HTML template: <select class="custom-select d-block w-100" id="test" ...

What is the best way to utilize multiple Ajax requests in order to generate server-side response data?

There are two separate Ajax queries that retrieve different parts of the required server-side data for DataTables. The first query retrieves 40 rows of records as a JSON string from a table, while the second query simply returns the total count for the tab ...

I'm keen on creating a marquee animation using Tailwind and Next.js

I'm working on creating a marquee animation using Tailwind CSS and Next.js, and I've made some progress. However, the issue I'm facing is that the items are not displaying one after the other smoothly; there seems to be a delay when the seco ...

What steps can I take to prevent the odd gaps from appearing in my horizontal flexbox gallery?

Take a look at this code: .gallery { display: flex; overflow-x: auto; resize: both; background-color: rgb(200, 200, 200); padding: 10px; height: 200px; } .item { display: flex; flex: 0 0 auto; max-width: 100%; } .item img { max-w ...

Error: StalePageException occurred in the wicket framework

I am currently using Wicket version 6.20. Within a Wicket page, I have implemented an AbstractDefaultAjaxBehavior to capture mouse clicks and their x,y coordinates: class CallFromJavaScript extends AbstractDefaultAjaxBehavior { private static final l ...