views:

62

answers:

1

I have page that POSTS AJAX to the server, and often the data will be Unicode.

This works most the time, but it appears that sometimes it's breaking and I'm can't seem to find the answer anywhere. I have been using encodeURI, but I'm not sure that's correct.

Here's a example of the code:

    $.ajax({
       type: "POST",
       url: "SomePage.php",
       data: "val1=" + encodeURI(unicodeVariable) + "&presentation=" + encodeURI(someUnicodeVariable),
       success: function(msg){

       }
     });                    

I'm guessing what's happening is sometimes a Unicode character includes an & that's breaking it.

What's the correct way to encode Unicode for an AJAX call with JQuery?

Thanks.

+3  A: 

Here's a good link that compares all of the encoding methods.

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() encodes also the "&" symbol:

encodeURI("&"); // "&"
encodeURIComponent("&"); // "%26"

Or you can just convert this line:

data: "val1=" + encodeURI(unicodeVariable) + "&presentation=" + encodeURI(someUnicodeVariable),

into an object:

data: {
    val1: unicodeVariable,
    presentation: someUnicodeVariable
}

And jQuery will automatically make sure the data is encoded, using encodeURIComponent().

Luca Matteis
Looks like changing it into an object and making sure the encoding was set to UTF-8 did the trick. Now all I need to do is figure out why the mdash character isn't getting stored correctly in MySQL.
Ryan Smith