I recently upgraded my dev server from PHP 5.4 to PHP 5.6 and I get a strange error while trying to test it. All my PHP code returns data as array or string via my main View, which uses the following code to send back the data as JSON to any Ajax query. (I deactivated the MIME type for testing purposes)
public static function SendData($data)
{
$response = array(
'status' => true,
'message' => $data
);
//header('Content-type: application/json');
exit(json_encode($response, JSON_HEX_APOS));
}
From that my Javascript code uses that data, normally immediately parse it to JSON since the MIME type tells JQuery to do so and process it. It worked fin in PHP 5.4, but since I upgraded, my response is modified by Jquery. Looking at the server's reponse in FireBug, I see it is valid JSON (Tested with JSONlint)
{"status":true,"message":"Didier Tartempion|dtartempion@example.com|Gestion de commerce"}
But when I check the following Jquery code in firebug
$.ajax({
url:"Connect.php",
type : 'POST',
data : data,
success:function(result)
{
//JSON processing, for now I debugg with
alert (result);
},
error: function(qXHR, textStatus, errorThrown)
{
alert(textStatus);
}
});
The result variable in success actually contains my response strangely formatted, it looks like this when using firebug watch :
"\n{"status":true,"message":"Didier Tartempion|dtartempion@example.com|Gestion de commerce"}"
As such, JQuery is unable to parse this and JSONlint says it is not valid. Is there something from PHP5.6 of even maybe the new server that could cause this strange behavior?
Thanks
I asked one of the senior programmers where I work and he suggested I checked in hex if any hidden character was added to the response. when converting to hex in PHP, no hidden character was found, but one appeared when trying to alert in JS.
I added this code to my success function
function toHex(str) {
var hex = '';
for(var i=0;i<str.length;i++) {
hex += ''+str.charCodeAt(i).toString(16);
}
return hex;
}
alert(toHex(result));
And I noticed that the hex character "feff" were added in the new server. Looking through the internet, I found out this is the BOM char to notice the browser that the file is encoded. I had to use this small PHP script and execute it on the server to get rid of the error.
Apparently things like this happens when you open the file in notepad++ for example and save it, it can mess up the encoding.