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

What is the best way to extract the text inside a div element based on the input value in a

I attempted to extract the innerText of a div along with the input values within it. For instance: <div> My name is Shubham, I work for <input type="text"/> for the last 5 years.</div> My objective is to retrieve all the text ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "ä" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Setting the width of an SVG element to match the width of the <text> element inside it

Within this JSFiddle project - https://jsfiddle.net/xtxd6r8t/ - there is an <svg> element containing text inside a <text> tag. Upon inspection of the <svg> and delving into the <text> element, it's noticeable that the width of ...

Ways to position a child element at the center of its parent container?

Hey there, is there a way I can achieve this specific layout without relying on position: absolute? Flexbox would be the preferred method. The main goal here is to have the middle element horizontally centered within its parent element, regardless of other ...

Do we actually need all of these DIVs?

Do you ever find yourself creating a div purely to house another element? Take for example, when designing a menu. You may create a div with specific styling and then place an unordered list within it. Alternatively, you could apply all the styling direc ...

Unexpected Output: Checkbox returning incorrect value using jQuery and PHP

I'm currently facing an issue where I'm trying to retrieve the value (true or false) of a checkbox and update the database for each row within a while loop. The problem is that the checkboxes only seem to respond to changes based on the first row ...

Tips for integrating highcharts plugins with highcharts-vue (highcharts vue wrapper)

Currently, I am utilizing the Vue wrapper for Highcharts called highcharts-vue(https://github.com/highcharts/highcharts-vue). However, I am facing an issue where I need to detect the event of a right mouse click (contextmenu) on the chart. To address this, ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

``In a WordPress plugin, a SELECT query for the database (utilizing WordPress, PHP, and MySQL) is

When trying to fetch records from a select query within a plugin, I encounter an issue where no records are returned and I receive the following error message in the web console. Can someone help me identify what mistake I might be making?: Object { rea ...

javascript calculate average based on user input array

There is a problem that I am trying to solve, but as a beginner it seems quite challenging. Here is the code I have written so far, however, when I run it only one window appears. Any advice or guidance would be greatly appreciated. var years = prompt(" ...

Guide on aligning all list items to the left using React Material-UI, incorporating fontAwesome icons, and styling with Tailwind.css

I am trying to align the text of my list items to the left. Here is what I have currently: https://i.stack.imgur.com/a5o5e.png Is there a way to left-align the text in this code snippet? import React from 'react'; import PropTypes from 'p ...

Customizing ExtJS 4's CSS reset specifically for tailored HTML inside components

I am currently in the process of upgrading an existing application from Ext 3.x to 4. I have successfully enabled Ext's scoped reset CSS option to prevent Ext from applying its CSS reset to my entire application. However, I am now facing a new issue. ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

Is it possible to transform a Vuejs project into Vue-Native?

I recently completed a Vue.js project and now I'm interested in turning it into a native app. I'm wondering if I'll need to completely rewrite the application using Vue-Native components, or if there is a way to convert my existing project i ...

Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar) let radius = [10,20,30]; let jsonradius = '[{'; for (let i = 0; i < radius.le ...

Integrating a YouTube video in the Google Maps info window with the help of Ajax technology

Currently working on a project for Udacity, my goal is to develop a neighborhood map using Google Maps API alongside Knockout and Ajax to integrate with another 3rd party API. A unique aspect of my approach is focusing on bars in the neighborhood and utili ...

Verifying user login on NodeJS through connection from an IIS-hosted website

I am currently upgrading an outdated CMS system and looking to implement a real-time chat feature. The existing CMS operates on IIS, MSSQL, and PHP. The chat feature will be hosted on a separate Linux box running Node.js and Socket.io After successfully ...

Set the height of the vertical scroll at a fixed 100% floatValue

Check out my creation at http://jsfiddle.net/ZygnV/ html, body { margin: 0; padding: 0; height: 100%; } .main-content-wrapper { height: 100%; overflow-y: hidden; white-space: nowrap; } .main-sidebar { display: inline-block; height: 1 ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...