UTF-8 Support in PHP and JavaScript

When I was developing phpLiveTalk, I wanted to send some URL encoded text in the AJAX response. I encoded the text using urlencode() php function, but the decoding on the client side (JavaScript) was an issue!

Why?

The JavaScript unescape() function does not understand the ‘+’ (Plus) in the encoding of ‘ ‘ (Space). Actually, it should be %20. So why not replacing all the + with %20 then unescape()!!!

Bingo… Solved.

Here’s the code you may use:

message = unescape(replaceAll(message,'+','%20'));

function replaceAll( str, from, to ) {
    var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}

Good Luck!

Leave a Reply