12

can anyone help? I have small procedure to read in an UTF-8 file with javascript using XMLHttpRequest.. this file has european characters like miércoles sábado etc.. Notice the accents..

But when being read in .. the characters are all messed up.. I have checked the file and it is perfect.. it must be the procedure for reading in..

heres an example i have file that contains, the file is perfect, it happens to be javascript but it doesn't matter.. any UTF-8 encoding file with special characters gives me the same issue

this.weekDays = new Array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");

but when returned and read by the procedure below it is like this (notice the funny characters in sabado and miercoles)

this.weekDays = new Array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");

Here is my procedure - its very small...

var contentType = "application/x-www-form-urlencoded; charset=utf-8";

var request = new XMLHttpRequest(); 
request.open("GET", path, false);
request.setRequestHeader('Content-type', contentType)

if (request.overrideMimeType) request.overrideMimeType(contentType);

try { request.send(null); }
catch (e) { return null; }
if (request.status == 500 || request.status == 404 || request.status == 2 || (request.status == 0 && request.responseText == '')) return null;

//PROBLEM HERE is with european charcters that are read in

print(request.responseText);


return request.responseText;
2
  • are you sure the file is in UTF-8? Did you set your text editor to save it with that encoding explicitly? Setting the request to UTF-8 is irrelvant, is the answer really in UTF-8 and the corresponding header set in the response?
    – jitter
    Commented Jun 20, 2009 at 7:07
  • thgis is old but for anyone stumbling on this, use the .overrideMimeType('text/plain; charset=utf8'); method of the xmlhttprequest object from MDN Using XMLHttpRequest
    – Nikos M.
    Commented Feb 11, 2015 at 12:57

5 Answers 5

28

Probably your file is not in UTF-8 then try this from javascript:

var request = new XMLHttpRequest();
request.open("GET", path, false);
request.overrideMimeType('text/xml; charset=iso-8859-1');
3
  • I'm sure my file is UTF-8 encoded, but the server didn't return this charset header, so this solved the problem.
    – Dinei
    Commented May 15, 2018 at 14:57
  • @Dinei if this snippet is working for you that means your output is not in UTF8. Some server providers could make modify your output. I suggest to try it in postman and check the headers.
    – Ricardo
    Commented May 16, 2018 at 8:48
  • I have a .json file which is UTF-8 encoded, but for some reason it is being served with Content-type: text/plain; charset=ISO-8859-1 header. Using overrideMimeType with charset=UTF-8 solved my problem.
    – Dinei
    Commented May 16, 2018 at 16:03
2

I'm having the same issue and I fixed in this way.

If you serve the js file containing the spanish days as UTF-8 and the if is NOT saved as UTF-8 it WONT work.

Save the file in your IDE as UTF-8 (ie. eclipse default for js files will be cp1252) and also serve it as UTF-8 char encoding.

If your app is java, do a filter with this code:

response.setCharacterEncoding("UTF-8");

have a good one

1
  • response.setCharacterEncoding("UTF-8"); is exactly what I needed.
    – Roger
    Commented Sep 9, 2022 at 22:01
0

EDIT: Seems that this answer, although accepted, is suboptimal, so for anyone coming here with a similar problem, check out Ricardo's answer

I think you have to use a different way to print the characters, for example, see the code at the end of this discussion:

<script>
  function getUnicode(num) {
    num = num.toString(16);
    if (num.length < 3) {
      for ( var i = num.length; i < 4; i++) {
        num = '0' + num;
      }
    }
    return ( "&#" + num + ";" );
  }

  for ( var i = 0; i < 65355; i++) {
    document.write(getUnicode(i));
  }
</script>
0
0

I also faced the same issue,I have solved in this way,

While In Get request, we are sending data through url So i decoded the url and get requested parameter through string operations

Consider if you are sending url like this, var ur1="getSubjectList.jsp"; ur1 +="?subjectlist=" +str+"&examId="+examId;

xmlHttp.open("GET", ur1, true); xmlHttp.send(null);

In getSubjectList.jsp, Use this-- String decodedParams= URLDecoder.decode(request.getQueryString(),"utf-8" );

String params[]=decodedParams.split("&");

     String subjectlist[]=params[0].split("=");
     String examId[] = params[1].split("=");
     String center = subjectlist[1];
    String exam = examId[1];

In this way,You can get the requested values

1
  • Sorry, but this question is about javascript, not java.
    – Jack G
    Commented May 23, 2018 at 16:38
0

I had a similar issue.

I had an AJAX request to the PHP server to check for duplicate names in the database.

When I sent the AJAX request through the GET method, the URL was encoded, so my variable got value on the server like %D0%A6%D0%B0%D0%BD%D0%BA%D0%BE%20%D0%9A%D0%B0%D0%BB%D0%B8%D0%BD%D0%BE%D0%B2.

To solve this I just used the urldecode function: [PHP urldecode(string $string)].[1] [1]: https://www.php.net/manual/en/function.urldecode.php

So, my JS function looks like this:

function checkName(e) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var responseJSON = JSON.parse(this.response);

            /*Do what you want with result here*/
        }
    };

    xmlhttp.open("GET", URL, 
        + e.target.value //input text
    , true);
    
    xmlhttp.send();
}

and my PHP code looks like this:

public function nameCheck($name){
    try{
        $name = urldecode($name);
        /*...do what you want with your variable after decoding...*/
    }
    catch(Exception $e){
        /*...*/
    }

}

I hope this helps, for everyone who has a project with PHP.

Cheers and happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.