When using xmlHttpRequest, the euro symbol may appear as a question mark

This dynamic script (taken from dynamicdrive) allows me to fill a div with the specified id dynamically:

    var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
    var loadedobjects=""
    var rootdomain="http://"+window.location.hostname
    var bustcacheparameter=""

    function ajaxpage(url, containerid){
        var page_request = false
        if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest();
        else if (window.ActiveXObject){ // if IE
            try {
                page_request = new ActiveXObject("Msxml2.XMLHTTP");
                }
            catch (e){
                try{
                    page_request = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                catch (e){}
            }
        }
        else
        return false
        page_request.onreadystatechange=function(){
            loadpage(page_request, containerid)
        }

        if (bustcachevar) //if bust caching of external page
        bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
        page_request.open('GET', url+bustcacheparameter, true)
        page_request.send(null)
    }

    function loadpage(page_request, containerid){
        if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
        document.getElementById(containerid).innerHTML=page_request.responseText
    }

Everything was running smoothly until I encountered an issue while loading a page containing special characters like a euro sign. Even though the codepages were set correctly on the page, it displayed a question mark instead. I lack the necessary knowledge of JavaScript to address this problem.

Thank you in advance for any insights you can provide!

NOTE: A friend informed me that saving the file in UTF-8 format resolves the issue when using this script. However, since I cannot guarantee that every page I load is UTF-8 encoded, my question is:

Is there a way to have the script automatically set the correct charset? Can the script be modified to adapt to the codepage of the file being loaded?

Answer №1

It appears that there may be an encoding issue present in your setup.

I highly recommend utilizing UTF-8 consistently, as it is widely recognized as the standard for the internet. Ensure that both the page making the ajax call and the dynamically loaded page are encoded in UTF-8 and served by the server with accurate headers (the headers should include something similar to

Content-type: text/html; charset=UTF-8
).

It is also considered a best practice to replace special characters with their HTML-friendly codes in web pages to prevent potential problems. For instance, use € for €.

Answer №2

Here's my theory, which seems to be supported by your recent updates:

  • When you create the remote document you're loading, you simply open your editor, type the € symbol on your keyboard, and save the file. Since you didn't specify an encoding, your editor defaulted to using the ANSI code page. The issue arises because the ANSI code page varies depending on your location. In Western Europe, for example, Win-1252 is commonly used and encodes the euro symbol as 0x80.

  • Similarly, when you create the target HTML document where you intend to insert the euro symbol, you follow the same steps and end up with a Win-1252 document. However, the web server is unaware of the encoding used. In many cases, it defaults to something like ISO-8859-1, which doesn't even include the euro symbol.

  • JavaScript interprets 0x80 as 0x80 when reading and writing the data.

  • The browser encounters 0x80 in an HTML document that's supposedly in ISO-8859-1 encoding. In this encoding, 0x80 is actually represented as a blank space.

Therefore, the issue doesn't lie in your JavaScript code (there's no error there), but rather in determining and utilizing the correct encoding for your site's files. Advanced editors offer encoding options for you to choose from.

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

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

In Redux, it is possible to add characters to an array but for some reason the remove action does not successfully reach the reducer

As a user types or erases characters, I am utilizing redux to update an array of characters. This allows me to set a success flag when the user correctly types the entire phrase. Currently, when typing in characters, the SET_INPUT action in redux fires of ...

What steps can be taken to fix the recurring node error "EADDRINUSE"?

Having trouble running an http server through node as I keep encountering the EADDRINUSE error specifically on port 5000. I've attempted using sudo lsof -i tcp:5000 and sudo kill -9 [PID]. Here's a snippet of the shell command: Borealis:BackEnd g ...

Using Next.js for dynamic routing with JSON arrays in getStaticPaths

I am currently facing an issue while trying to incorporate a json file with multiple arrays into my Next.js application. The structure of the json file is quite complex, and I'm unsure about how to convert it into a format that can be effectively util ...

Display HTML containing a <script> tag within a REACT component

Looking to embed the following HTML code within a React component: <form action="/process-payment" method="POST"> <script src="https://www.example.com/payment-script.js" data-preference-id="$$id$$"> </script> </form> I ...

Address NPM vulnerabilities through manual fixes

I downloaded a repository and ran an npm install, but encountered an error at the end. Now, every time I run npm audit, I receive the following message: found 18 vulnerabilities (5 low, 12 moderate, 1 high) in 15548 scanned packages 9 vulnerabilities requ ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Verify whether the default export of a file is a React function component or a standard function

Trying to figure out how to distinguish between modules exporting React function components and regular functions. Bun employs file-based routing, enabling me to match requests with module files to dynamically import based on the request pathname. Conside ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...

Charting data from MongoDB with Highcharts column chart

Having trouble creating a column chart with Highcharts in Node.js, fetching data from MongoDB. Specifically stuck on the series option - any help is appreciated. Here's an excerpt of my code in the EJS file: <html> <head> <meta ht ...

Accessing a value in JSON (beginner level)

Hello everyone! I have come across a URL: . My goal now is to extract the value (Price) of a specified key (name). I am aware that there have been similar inquiries in the past, but unfortunately, I haven't been able to make it work as JSON is relat ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

refreshing the webpage with information from an API request

I am completely new to web development, so please bear with me. I am attempting to make a simple API call: const getWorldTotal = async () => { const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/cov ...

Troubleshooting problems with jQuery Validate and dynamically adding rules through ajax requests. Is there a potential issue with variable scope

I've been encountering some difficulties with the code snippet below: var counter = 0; $('#add_row').click(function(e) { $('input[name="user_email[' + counter + ']"]').rules("add", { required: true, ...

Pause before proceeding to the next iteration in the loop

I am currently facing an issue while trying to send a message through an API using a function. The function returns a value called messageLogId, which I'm attempting to update in the main loop at Attendence. However, when executing the code, the value ...

When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not! var url = './images/pros/imagefile.png'; var http = new XMLHttpRequest(); http.o ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...