JQuery AJAX Call with Unicode. Correct way to send Unicode POST data?

I have a POSTS AJAX page on the server, and often the data will be Unicode.

This works most of the time, but it seems like it breaks sometimes and I can’t find the answer anywhere. I use encodeURI, but I'm not sure if this is correct.

Here is a sample code:

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

I assume that sometimes the Unicode character happens and that violates it.

What is the correct way to encode Unicode to invoke AJAX using jQuery?

Thanks.

+4
source share
1 answer

Here is a good link that compares all encoding methods.

Finally, the encodeURIComponent () method should be used in most cases when encoding a single component of a URI. This method will encode certain characters that are usually recognized as special characters for the URI so that many components can be included. Note that this method does not encode a character, since it is a valid character in a URI.

encodeURIComponent () also encodes the "&" character:

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

Or you can just convert this line:

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

to object:

 data: { val1: unicodeVariable, presentation: someUnicodeVariable } 

And jQuery automatically checks if the data is encoded using encodeURIComponent ().

+6
source

Source: https://habr.com/ru/post/1299976/


All Articles