I'm trying to send data as UTF-8
over Ajax, but it's changing some data in unicode
. I'll explain it with two short examples:
A simple POST (without ajax)
<form accept-charset="UTF-8" method="POST" action="test2.php">
<input type="text" class="" name="text">
<input type="submit" class="button" value="Submit">
</form>
Meta and PHP headers are always set:
<meta charset="utf-8">
header("Content-Type: text/html; charset=utf-8");
If I submit an Arabic letter (ب
), and use strlen()
it will return 3. If I use mb_strlen()
it will return 1. This is all good as it should be.
Now the Ajax version. The form, headers and meta are the same. But onsubmit() calls this ajax in Javascript:
... (initiating HttpReq)
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader("charset", "utf-8");
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...
if (self.xmlHttpReq.readyState == 4) { ... }
Now the same test gives for strlen()
6 and for mb_strlen()
also 6. The ب was actually converted to 6%u0628
somewhere in the Ajax process.. And this does not happen with a normal POST
(example one).
What am I forgetting/doing wrong in the Ajax process ?
i use alot ajax and always use only utf8 and never had a problem , i'm mostly on chrome and safari ios
maybe try changing ur ajax script by removing all the headers.and using the new
FormData
(should work on most modern browsers) ... sure not on all.document.forms[0]
means it takes all the fields from first form in your page. else give it an id and calldocument.getElementById('myform')
i also don't use anymorereadyState
...onload
to return the response in postresponsefunction u write
this.response
here is a complet working php script with post & ajax file is named 'test.php'
ie