Damian
Damian

Reputation: 3050

Non ASCII character sended using Ajax cannot be decoded properly in Java

I am sending an AJAX request with jQuery post() and serialize. That uses UTF-8. For example when 'ś' is a name input value , JavaScript shows name=%C5%9B. I have tried setting form encoding without success.

<form id="dyn_form" action="dyn_ajax.xml" style="display:none;" accept-charset="UTF-8"> 

The same happens with encodeURI(document.getElementById("name_id").value). I'm using Servlets on Tomcat 5.5.

Upvotes: 0

Views: 675

Answers (3)

dodecaplex
dodecaplex

Reputation: 1171

I always had a hard time convincing the request object to decode the URIEncoded strings correctly.

I finally made the following hack.

    try {
        String pvalue = req.getParameter(name);
        if (null != pvalue) {
            byte[] pbytes = pvalue.getBytes("ISO-8859-1");
            res = new String(pbytes, "UTF-8");
        }
    } catch (java.io.UnsupportedEncodingException e) {
        // This should never happen as ISO latin 1 and UTF-8 are always included in jvms.
    }

I don't really like this, and it's been a while since I stopped developing servlets, but it was already on tomcat 5.5, so it's worth trying.

Upvotes: 1

Nabor
Nabor

Reputation: 1701

If it's really UTF-8, try decodeURIComponent.

Upvotes: 1

Naor
Naor

Reputation: 24103

I had this kind of problem many times.
Verify your pages are saved in UTF-8 encoding.

Upvotes: 1

Related Questions