XMLHttpRequest changes the contents of UTF-8 encoded text

Encountered a challenging issue while processing a large XML file on the client side. Some unicode characters are being replaced with unreadable sequences, causing the server to be unable to parse the XML properly. Here is how I approached testing and handling this problem:

var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);

Even though logging displays the correct string:

<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />

Upon inspection in the request (Chrome dev tools) and at the server side, it seems that the string has been altered:

<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />

The original encoding of the XML file is UTF-8 as well. The same issue persists when utilizing jQuery for this task.

Answer №1

  1. Ensure that the use of overrideMimeType specifies "UTF-8" in either uppercase or lowercase
  2. Verify that the string used before JavaScript calculation is encoded in utf-8 (check page charset)
  3. Apply escape/encodeURIComponent/decodeURIComponent before transmitting it to the server and unescaping it on the server
  4. Experiment with application/x-www-form-urlencoded and send XML as plain text

NOTE: The modified string is stored in ISO-8859-15 encoding

Answer №2

It appears to be the case.

I possess a JSON data parameter containing the string "Lääke" (Finnish word), which I transmitted to the server through AJAX.

In this instance, the server application failed to receive 'ää' and instead received '??':

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    response = this.responseText;
    if (response === "OK") {
        window.location.assign("ackok.html");
    }
    else {
        window.location.assign("ackerror.html");
    }
  }
};
xmlhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);    
xmlhttp.send();

However, in this scenario, the server successfully received 'ää':

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    response = this.responseText;
    if (response === "OK") {
        window.location.assign("ackok.html");
    }
    else {
        //orderStatusElement[0].innerHTML = "<b>There was an issue on the server side. Please try again later</b>";
        window.location.assign("ackerror.html");
    }
  }
};
xmlhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
xmlhttp.send(); 

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

It is not possible to update a component while another component is being rendered. To identify the erroneous setState() call within the `MyApp` component

Whenever I navigate from the main page to the login page, I encounter this error. The Header component is used as a child component throughout my app. The error message reads: Cannot update a component (Header) while rendering a different component (MyApp ...

Ionic 2's Navigation Feature Failing to Function

I need to implement a "forgot password" feature on my login page. When a user clicks the button, they should be redirected to the "forgot password" page. Below is the code snippet from my login.html <button ion-button block color="blue" (cli ...

Using JavaScript to make an asynchronous call to the server via AJAX

Is it true that clients can block JavaScript in their browsers? If so, what impact does it have on AJAX calls - do they still function properly? ...

Display images that have been uploaded on the page either as a grid view or a list of

In my Reactjs application, I am uploading multiple images to Azure Blob Storage. On a page, there is a button to open the upload form. Once the upload completes, I want to display all these images on the same page. Since the images have different aspect ...

Tips for waiting for a Promise to resolve before returning a new Promise

In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all exis ...

Creating a jQuery-powered assistance pop-up: A step-by-step guide

On various websites, you may have seen a help box labeled with a question mark icon [?], which, when hovered over, displays a small box of additional information. I discovered that these are typically created using a combination of Javascript and jQuery. ...

What is the best way to utilize static methods for transferring authentication tokens to an API class?

Recently, I developed an API class to handle network calls in redux saga. The structure of the class is as follows: export default class ApiService { constructor(bearer) { this.instance = axios.create({ ... ...

Global JavaScript functionality is disrupted by the webpack runtime chunk

After embedding a VueJs application into an existing site with its own set of JavaScript libraries, I encountered an issue. The runtime chunk in my application is calling the existing scripts from the site, resulting in multiple event listeners being added ...

Tips for integrating global functionalities such as Create, Methods, and Mounted from a plugin into Vue

In certain scenarios, I prefer not to utilize mixins in my Plugin. Instead, I am working on incorporating custom methods like `created()`, `mounted()`, and `methods{}` so that I can access its property when the component loads and execute my own custom me ...

What is the best way to implement validation for individual elements within an array that are being displayed on a webpage using a for loop?

Currently, I am utilizing Vue JS within the Vuetify framework to build a dynamic form: <v-text-field v-for="items in itemsArray" :key="items.id" v-model="items.data" :label="items.name" ></v-text-field> ...

How can I use JavaScript to add a search text to the selectpicker searchbox in Bootstrap, and then automatically display the search results in the dropdown menu?

In the process of developing a web application with Razor Pages ASP.NET CORE 3.0, I have integrated a Bootstrap "selectpicker" dropdown with the attribute "data-live-search= true". The dropdown is populated with the names of employees from my model. Below ...

JavaScript: How can I execute a count that pertains solely to elements that are currently visible

Using jQuery, I have implemented a search functionality that hides items in a list that do not match a given string. The code loops through a list of divs and utilizes $(this).fadeOut(); to hide the elements. While this functionality works effectively, I ...

Seeking the value of a tab text using Selenium's web driver

Greetings! Currently, I am exploring the integration of selenium webdriver with mocha and node js in order to automate testing for a Single Page Application (SPA). My objective is simple - to locate a specific tab and perform a click action on it. The HTML ...

What is the correct way to chain custom callback functions using .queue()?

I am currently grappling with the concept of chaining custom functions: My code snippet looks like this: show_loader(0, function() { open_box($target_open, event.value, '.wide-col', function() { hide_loader(function() { ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

The results of an AJAX file upload operation

Currently, I am utilizing an AJAX File Uploader from the following link: The code I am using is as follows: function ajaxFileUpload() { $('input[type=file]').each(function () { if ($(this).val() == "") { return true; ...

Having an issue with retrieving value from a textfield in JavaScript

<input id="checkOldPassword" type="button" title="Check New Password" value="Check New Password" onclick="checkPassword()" /> <input id="newPassword" type="text" maxlength="8" min="8" /> <script language="javascript"> function checkPassw ...

Find the offsetTop value of one element and apply it to a different element

In my current project, I have a list of items where each item, when clicked, should reveal another view next to it. The challenge I am facing is setting the offsetTop of this view to match the item's offsetTop. While I have a solution using jQuery, I ...

Ways to gather a compilation of active scripts, including those that have been dynamically loaded

My goal is to find a specific script among the scripts currently loaded on the page: if($('script[src="' + sn + '"]').length == 0) $('head').append('<scr' + 'ipt src="' + sn +'"></scr' ...