I have a Jquery code getting data from ajax call.
$.ajax({
type: 'GET',
url: 'php/upd_dashboard.php',
data: {'name': 'GET_ANUAL_TOTAL_OBJECTIF'},
success: function(data){
list_total_objectif=data;
},
dataType: 'JSON',
async: false
});
the file upd_dashboard.php, get data from MySql database, and return json result.
echo json_encode($result);
I have no problem when executing this code in localhost, but when I deploy the site I can't get the result of json_encode.
by inspecting that in Chrome, I get a character '\ufeff' at the beginning of the json result !!
Chrome inspection result
Is it a problem of encoding?
Regards,
Hamza.
You can try doing ob_clean(); before sending out json output
ob_clean();//clears the output buffer
echo json_encode($result);
But it seems your $result is just malformed. Is it a string or an array? No character encoding issues there anyway
From what I've found on Google, \ufeff is the Byte Order Mark.
So you probably have your PHP source files in UTF-8 With BOM.
Some PHP versions don't like that and send the BOM output.
Try converting all your PHP source files to UTF-8 Without BOM and it should fix the issue.
Related
Environment: PHP 5.3.5 MySQL Server 5.5.8, jquery version 1.6
Using Ajax to auto-populate a dropdown list of countries.
I keep getting this error and I have tried numerous things. Such as surround the $results with "'$results'" before encoding. The error still persists.
Here is the an example of output:
array(1) {
[0]=>
array(4) {
["id"]=>
string(2) "45"
[0]=>
string(2) "45"
["nicename"]=>
string(16) "Christmas Island"
[1]=>
string(16) "Christmas Island"
}
}
Here is the ajax (I even tried to change success to complete - the error code is just duplicated if I do that.
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: {handler:"getCountries", nli:"-1"},
dataType: "json",
success: function(results){
//results = $.parseJSON(results);
var resultStr = "";
for(var x in results)
resultStr = resultStr + results[x];
alert("RESULT" + resultStr);
//populateDropDown(results);
},
error: function(xhr, status, error){
alert(xhr+ "| ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xhrStr = "";
for(var x in xhr)
xhrStr = xhrStr + xhr[x];
alert(xhrStr);
}
});
After I encode the json string in php I am escaping for special characters like so:
if (!empty($results)){
$json = json_encode($results);
//$json = form_safe_json($json);
echo $json;
}
function form_safe_json($json) {
$json = empty($json) ? '[]' : $json ;
$search = array('\\',"\n","\r","\f","\t","\b","'") ;
$replace = array('\\\\',"\\n", "\\r","\\f","\\t","\\b", "\'");
$json = str_replace($search,$replace,$json);
return $json;
}
After I encode the json string in php I am escaping for special characters
You don't need to do that -- json_encode() does all the necessary escaping for you, and in fact doing so is probably breaking the valid JSON that json_encode() has produced for you.
[EDIT]
To be clear: PHP's json_encode() function produces valid JSON from any input. (The only thing you need to test for is false if it fails, but even that will parse correctly in jQuery if you echo it, since an empty string is valid JSON).
If your program echos the output of json_encode(), and nothing else, then your program will be serving valid JSON and will not get the JSON parsing error in your JS code.
If your program echos anything else, or if you modify the JSON string before sending it, you may very well get errors.
Things to watch out for:
Don't try to send multiple JSON strings one after the other using multiple calls to json_encode(). This will be invalid JSON. Encode everything you want to send using a single call to json_encode().
Beware of PHP sending unwanted characters (particularly white space and UTF-8 BOM characters) which can cause errors in many situations.
If errors persist, load your JSON URL into the browser direct and view the source. You may see the error straight away. If not, copy and paste the JSON string into one of the JSON test sites on the web and see what it reports. This may help explain the problem.
If you're on PHP 5.4, you can use the PRETTY_PRINT option in json_encode(). This may help you with your debugging.
Perhaps json_encode() could be of some use? http://php.net/manual/en/function.json-encode.php
I am not sure what you try to achieve with the form_safe_json command.
The text string returned from:
$json = json_encode($result);
will contain correctly formated json and should not be further escaped in case you wish for the Javascript to parse it correctly. The escaping made by form_safe_json will break the json.
So im trying to send data from an HTML page through Ajax, to a PHP page.
Thats the piece of jQuery code that im using:
$.ajax({
url: "test.php",
type: "POST",
data: {
name: "João"
}
}).done(function (data) {
alert(data);
})
As you can see, the parameter im sending is "João". Before making the Ajax request jQuery encodes it on the background, "João" becomes "Jo%C3%A3o" which is double encoded UTF-8.
My problem arises when the request is sent and PHP tries to decode it on the background. PHP decodes automatically it only once when I use $_POST, so instead of getting "João" I get "João". That happens because PHP is decoding every % individually, so %C3 becomes à and %A3 becomes £.
If I try to decode it manually through utf8_decode() it will work, but im here to know if there's a better solution. What I really need is a way for PHP to decode my data correctly, even if it's double-encoded, or even triple-encoded.
That's not double-encoded, it's correct UTF-8. It looks like the PHP is expecting latin-1 encoding instead, and is showing you what the same bytes would mean if they were not
UTF-8.
In this case, since your characters seem to be below 0xFF, you could also URL-encode them first as Jo%E3o in latin-1 if you can't work out how to have PHP recognize UTF-8.
i am generating a json string using JSON.stringify and my json string will be like
jsonstring=[{"step1":[{"nm":"John & joe"},{"title":"Hello & hai"}]},{"step2":[{"desc":"1234"},{"usr":"abc#xyz.com"}]}]`
i am escaping & with \& and sending this json string to server through ajax.
$.ajax({
url:"test-usr-data.php",
type:"post",
data:"usrdata="+jsonstring,
success: function(response){
console.log("data is "+response);
},
complete:function (jqXHR, textStatus){
console.log("ajax Request completed"+textStatus);
}
});
The problem is with & char in json string, even though i am escaping & to \& data is not posted to server but ajax request status is success.
I tried removing & from json string it works fine and data is posting to server correctly.
Can any one help me in correct way to escaping & in json string.
Who told you that escaping in URL's works by prepending a backslash?
jQuery will take care of it, just do
data: {usrdata: jsonstring},
FYI: You could use encodeURIComponent as well
data: "usrdata=" + encodeURIComponent(jsonstring),
The way to URI encode a & is as %26, given that 0x26 (38) is the ASCII code for that character.
But don't, use the data: { key: value, ... } way of passing parameters to $.ajax instead, and have jQuery do it all for you.
I perform an AJAX request to a PHP script in JavaScript and by using the jQuery library.
Here is my command which performs the AJAX request :
$.ajax({
async: "false",
cache: "false",
data: {login: strLogin, password: strPassword},
datatype: "text",
error: connexionAjaxError,
success: connexionAjaxSuccess,
type: "POST",
url: "./Connexion"
});
".Connexion" is a URL redirection to my PHP script.
connexionAjaxError is a JavaScript function inevitably executed as soon as the HTTP response is received.
The reason : My PHP script results to a text/plain page with HTTP status code equal to 500.
Here is the most relevant part of my PHP script :
header("HTTP/1.0 500 Internal Server Error;
Content-type: text/plain;
charset=ISO-8859-1");
echo "été";
Here is the signature of the connexionAjaxError callback function :
function connexionAjaxError(jqXHR, textStatus, errorThrown)
My PHP results to the string "été".
My PHP internal encoding is ISO-8859-1 so the result string is encoded [e9 74 e9] in hexadecimal notation.
But jqXHR.responseText in the connexionAjaxError callback function contains a 1-character string.
I have used the charCodeAt method of the JavaScript String object to get the unicode (UTF-8 ?) code for the character.
The character is encoded 65535 in decimal notation equivalent to [ff ff] in hexadecimal notation.
I do not understand why jqXHR.responseText does not contain the 3-character string "été".
I am not an expert in JavaScript but I suppose jqXHR.responseText can only contains a string encoded in UTF-8.
So the string "été" in jqXHR.responseText would be encoded [c3a9 74 c3a9] in hexadecimal notation.
I have retrieve the UTF-8 code for the character "é" from the following web site : http://www.utf8-chartable.de/
I make a lot of development in Spanish and I've noticed a few things that might help you, since I've gone through this already:
The charset in the header function should be UTF-8.
Also, the FILE itself (the PHP script) must be saved in UTF-8, you can easily achieve this if you edit the file with Notepad++ and select the encoding to be UTF-8 without BOM.
Same goes for your javascript and HTML files, they should all be encoded with UTF-8 without BOM rather than ANSI.
Let me know!
Try to set the Contenttype like this in your call, as far as I know jQuery Ajax is always utf-8 if not specified.
$.ajax({
...
datatype: "text",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
error: connexionAjaxError,
success: connexionAjaxSuccess,
type: "POST",
...
});
Edit:
If my answer isn't helpfull, it might help if you check the servers charset configuration, and also post it.
The following jQuery ajax function runs a PHP script that queries a MySQL database containing entries that are encoded as UTF-8:
function searchLocations() {
var stateSelected = $("#stateSelect").val();
$.ajax({
url: 'ajax/json.php',
dataType: 'json',
data: 'state='+stateSelected,
success: function(data) {
placeMarkers(data.markerdata.markers);
}
});
}
The JSON object returned to the function contains the longitudes and latitudes of map marker objects as well as a name to display in an info window when each marker is clicked.
Every name loads fine, and is displayed without a problem except for a single name which contains the character "ñ". This name is returned in the JSON object as "null". How can I make this name display properly?
I used to have this problem and I found there was two options:
In PHP convert all characters into HTML friendly characters using the PHP function htmlentities (http://php.net/manual/en/function.htmlentities.php) before returning it to the jQuery function.
If that fails or the characters are not converted you could try using base64 encode and decode. In PHP you can encode the data using base64_encode function (http://php.net/manual/en/function.base64-encode.php). Then in jQuery you could use one of many base64 encode and decode plugins to decode the data. I have used this plugin successfully in the past: http://plugins.jquery.com/project/base64-encode-and-decode
Failing both those options it may be worth looking at the character set used by your page. Try and use UTF-8 to encode your HTML and see if that helps.
Without using jQuery and AJAX if you did a basic PHP page that queried the data in question and prints the name out does it still not display correctly. If it doesn't it could also be a character set issue with MySQL.
Hope any of these pointers help. Let me know how you get on.