How to properly encode UTF-8 for JavaScript and JSON?

I have a problem creating an input validation hash. JavaScript submits data to API and API validates the sent data with json_encode. Basically it works like this:

$input=array('name'='John Doe','city'=>'New York');
$validationHash=sha1(json_encode($input).$key); // Key is known to both servers

If PHP connects to another server, then everything works. It also works through JavaScript (I have a custom sha1() function there as well):

var validationHash=sha1(JSON.stringify({'name':'John Doe','city'=>'New York'})+key);

My problem comes when the string contains UTF-8 characters. For example, if one of the values is:

Ränisipelgasöösel

Then PHP server that receives the command converts it to this after JSON encoding:

R\u00e4nisipelgas\u00f6\u00f6sel

I need to do this in JavaScript as well, but I haven't been able to work out how. I need to make sure that I send proper validation hash to the server or the command fails. I found from Google that unescape(encodeURIComponent(string)) and decodeURIComponent() could be used, but neither gives me the same string that PHP has and validates with.

UTF-8 is used on both client and server.

Any ideas?

Answers


It does not seem to be possible. The only working solution I have found is to encode all data with encodeURIComponent() on browser side and with rawurlencode() on PHP side and then calculate the JSON from these values in arrays.


Need Your Help

exception when converting to int32

c# linq-to-sql

When executing this code, I receive an error on the last line. How should this be rewritten to avoid the exception?

How to change Max Schedulable Application for Hadoop Apache 2.2

hadoop yarn

I am playing around with capacity-scheduler. I have updated number of total applications running on cluster and total number of applications that can be submitted by user more than 1 respectively. ...