I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text.

var xmlHttp = new XMLHttpRequest();
          xmlHttp.onreadystatechange = function() { 
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
               { 
              window.alert(xmlHttp.getAllResponseHeaders()); 
                 document.getElementById("captchaDiv2").innerHTML = "<img src=\"data:image/png;base64," + xmlHttp.responseText + "\"/>";
               }
          }
          xmlHttp.open("GET", captchaSrc, true); // true for asynchronous 
          xmlHttp.send(null);

The response header indicates that the type is image/png:

https://i.stack.imgur.com/HG4gK.png However, upon attempting to insert it into the HTML, the output looks like this: https://i.stack.imgur.com/vR8Vp.png

Could you please provide insights on what might be causing this issue? I have already attempted using btoa() with and without encoding, but it did not yield any positive results.

Answer №1

This response references valuable information from a discussion on Stack Overflow (https://stackoverflow.com/a/11562550/266561). In summary, the conversion of XHR strings to base64 encoding can be challenging due to potential corruption when converted to UTF-8, rendering the base64 string invalid. Attempting to use btoa(xmlHttp.responseText) may result in errors in Chrome, particularly with non-ASCII characters present.

However, there is a workaround available. Begin by creating an empty <img id="captchaImg" /> element for easier embedding of the new source. Then,

var xmlHttp = new XMLHttpRequest();
xmlHttp.responseType = "arraybuffer";
xmlHttp.onreadystatechange = function() { 
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 
    document.getElementById("captchaImg").setAttribute('src', 'data:image/png;base64,' + btoa(String.fromCharCode.apply(null, new Uint8Array(xmlHttp.response))));
  }
}
xmlHttp.open("GET", captchaSrc, true); // true for asynchronous
xmlHttp.send(null);

The crucial aspect here is setting

xmlHttp.responseType = "arraybuffer"
to maintain data integrity and prevent corruption. In terms of compatibility, typed arrays are supported from Internet Explorer 10 onwards and even in older versions like Safari 5.1 (the last version for Windows).

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

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

The font weight is failing to take effect

I'm having an issue with the font-weight in my CSS. On my website, I'm trying to decrease the font-weight but even the lightest weight (100) looks too heavy like this: https://i.stack.imgur.com/6dwFa.png However, I want it to look more like this ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

A recursive function enhanced with a timeout mechanism to avoid exceeding the stack call limit

Trying to search for images on any object of various depths using a recursive function can lead to a Maximum call stack size exceeded error in certain cases. A suggested solution here involves wrapping the recursive function in a setTimeout, but this seems ...

Advancing in the Mozilla fashion

Having an issue with my progress bar design... When viewed in Chrome, the value of the progress bar appears in red due to CSS styling I applied... But when opened in Mozilla, it shows up as a dull grey color. progress[value] { width: 250px; height ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

Error: The function of forEach is not applicable to todoList

_serilizedList(todoList){ let serialized = '*My to-dos:*\n'; todoList.forEach((t, i)=> { serialized += '*${i}* - ${t}\n'; }); return serialized; } Unexpected TypeError: todoList.forEach is not ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

What is the best way to eliminate the final character in an input value once it has passed through regex validation in Angular8

Hello! I am attempting to remove the last digit of a string and update the input value each time my function checks if the input value passes a regex test on keypress. Initially, it works correctly, but then it adds an extra digit. After that, it works a ...

What is the best way to incorporate products as components into the cart component?

ProductCard import React from 'react'; import { Card, Container, Row, Col, Button} from 'react-bootstrap'; import Cart from './Cart'; import './ItemCard.css'; function ProductCard(props){ return( <Car ...

Find all elements located in between two headers with varying ids

I am trying to select a specific range of elements in between two headers, excluding everything after the second header. For example, I want to select elements 1-5 from the following code snippet: <!DOCTYPE html> <html> <head> <link r ...

Using jQuery to load content into a jQuery UI dialog box

I am looking to implement a pop-up that displays content from another asp page. To achieve this, I am using jquery.load to load the page into a div and jquery-ui.dialog. This is my code: <div id="dialog"></div> Inside the document ready fun ...

What is the best way to include CSS code in the output display?

I'm looking to customize the appearance of my table rows and cells. Specifically, I want the cell file name, size, etc., to be colored blue while each row should have a different color on hover. I've attempted to achieve this using CSS and variou ...

Tips for eliminating the border surrounding the entire table in Material-ui

Is there a way to edit a table in Material-ui without displaying it as a card? I'm looking to remove the border around the entire table, but I couldn't find any information on how to do that. Can someone help me out? Here is a link about the com ...

Solving the Color Change Mystery in Your Dash Application

My goal is to design a sleek black dashboard, so I acquired a CSS stylesheet that should give my dashboard a black theme. Following the instructions, I created an assets folder in the root directory of my app and added my CSS and JavaScript files there. Da ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Mastering the art of positioning images using CSS and HTML in email marketing

Currently in the midst of designing an email template for a new project. I have set up a table, with one row featuring some stripes and the next row showcasing a black bar to match the site's layout. My question is: Is there a way to incorporate an i ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

Encountering difficulties in accessing files displayed by serve-index in Express

My Node.js server using Express seems to be working fine for displaying directory contents, but I'm running into an issue when trying to access individual files. After clicking on a file listed in the directory, I keep getting an error message that sa ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...