I am using jQuery.parseJSON() to parse a response from jQuery.ajax() call to a PHP script.
The code works except on some server the characters 0000 are inserted at the start of the response string causing jQuery.parseJSON() to fail.
I can not figure how those character are being inserted, any ideas?
The characters are not in the PHP encoded string before echoing response.
Here is the scenario:
PHP script creates JSON string with:
$html = json_encode(myArrayOfValues);
echo $html
jQuery.ajax receives encoded string in:
....success: function(html, textStatus){
var response = jQuery.parseJSON(html);
....
To fixed the problem I added function that removes inserted characters and changed:
var response = jQuery.parseJSON(html);
to:
var response = parseJSONResponse(html);
Where:
function parseJSONResponse(html){
var foundChar = html.indexOf("{");
if(foundChar > 0 ){
html = html.substring(foundChar);
}
var response = jQuery.parseJSON(html);
return response;
}
Ultimately, it works but I'd like to know where the inserted characters are coming from and if there is a way to prevent them being inserted.
This could be a character encoding related issue. \u0000 is the NULL character. Although this could just be a coincidence it seems worth looking into.
I think the preferred character encoding for json is utf-8. Try adding this to the head of your calling page and see if it resolves the issue:
<meta charset="utf-8">
Hope that helps!
Related
I have the following code that converts json into an array:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
$jarray = json_decode($decodedstr, true);
echo "<pre>";
print_r($jarray);
echo "</pre>";
but my $jarray keeps returning null... I dont know why this is happening.. i have already validated my json in this question:
validated json question could anyone tell me what i am doing wrong? or what is happening. Thanks in advance.
when i echo my $str i get the following:
You are passing to json_decode a string that is not valid JSON, this is the reason NULL is returned.
As I see from comments inspecting the error code generated gives 4 that corresponds to the constant JSON_ERROR_SYNTAX that just means the JSON string has a Syntax Error.
(See http://php.net/manual/en/function.json-last-error.php)
You should inspect (echo) what you get from
$str = file_get_contents('http://localhost/data.json');
(You may edit your answer and post it - or a portion of it)
For sure it is not valid JSON; the problem lies there: in data.json.
Then as you fix things and get from data.json what is expected I would ensure you really need to use html_entity_decode on the fetched data.
It would be "weird" to have html encoded JSON data.
UPDATE
Looking at what you get from data.json it seem the JSON data contains actually HTML entities (as I see the presence of s)
This is actually weird, the right thing to do would be to fix how data.json is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json.
We can't deepen this here as I don't know where does data.json come from or the code that generates it. Eventually you may post another answer.
So here is a quick fix provided that the right approach would be what I just suggested above.
As you decode html entities, non breaking spaces turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data.
The idea is to remove these characters; your code becomes:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
// the character sequence for decoded HTML
$nbsp = html_entity_decode( " " );
// remove every occurrence of the character sequence
$decodedstr = str_replace( $nbsp, "", $decodedstr );
$jarray = json_decode($decodedstr, true);
from php manual
http://php.net/manual/en/function.json-decode.php
Return:
... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit
So, surely the JSON string passed to json_decode() is not valid:
maybe because of html_entity_decode
I am using javascript and php and need to pass some HTML in the JSON variable (PHP->JS).
Unfortunately, due to some environmental constraints I am limited in the jQuery I can use. Using things such as jQuery.parseJSON(str) and $.parseJSON(str) throw unexpected token errors.
Therefor I need a purely javascript approach to handling html in a JSON variable. Currently, the HTML string is just printed as a string on the page, though I need it to take effect as HTML.
My JS code is as follows:
document.getElementById("activeDescription").innerHTML = response['description'];
and the results ends up just being text on the HTML page as follows:
<p>helloworld</p>
whereas I expect just
helloword
to be displayed on the HTML page. On alert(response['description']) I receive
<p><span class="
EDIT
When I use
jQuery.parseJSON('{"name":"John"}');
everything is peachy but this code
jQuery.parseJSON(response['description']);
gives me an "Uncaught SyntaxError: Unexpected token & " error
Most probably a encoding problem. You can fix by decoding the characters.
In javascript:
var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;
In PHP, look at this link: http://www.php.net/manual/en/function.htmlentities.php
I need to pass a url to a php page. the url may or may not contain special characters and encoded variables.
for example consider the ajax request.
var url = 'http://siteaddr.com/abc%20cdf%202012%20movies%20software/';
$.get('check_link.php',{url:url},function(){
//some function
});
the echo result of variable $_GET['url'] in the php page is http://siteaddr.com/abc cdf 2012 movies software/
the %20's are converted into spaces. I need to receive the url as it is.
tried encoding and decoding the url. but I didn't got the result as i need.
You're not supposed to define a variable with the name that will be used as a key.
Encoding the URL again, before sending it will make PHP decode the double encoded URL.
var link = 'http://siteaddr.com/abc%20cdf%202012%20movies%20software/';
$.get('check_link.php',{url: encodeURIComponent(link)}, function(){
//some function
});
// Double encoded URL: Note that % has become %25
// http%3A%2F%2Fsiteaddr.com%2Fabc%2520cdf%25202012%2520movies%2520software%2F
http://jsfiddle.net/zNqac/
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.
All,
I make a JSON request to a web server using PHP and it returns me a JSON response in a variable. The JSON response will have lots of keys and values. The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
$response = json_decode(utf8_encode($jsonresponse));
Now, I have to pass the same value to the server in a JSON request to do some stuff. However, when I pass
$jsonrequest = json_encode(utf8_encode($request));
to the server, it fails.
The following code succeeds in reading special characters and displaying it to the UI. But fails if I have to pass the utf8_encode value to the server.
The current whole roundtrip code is as under:
$requestdata = json_encode($request);
$jsonresponse = //Do something to get from server;
$response = json_decode(utf8_encode($jsonresponse));
How can I modify it such that I pass the exact value as to what I receieved from the json response from the server?
The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
JSON data already comes encoded in UTF-8. You shouldn't convert it to UTF-8 again; you'll corrupt the data.
Instead of this:
$response = json_decode(utf8_encode($jsonresponse));
You should have this:
$response = json_decode($jsonresponse); //already UTF-8!
Set This into your php connection :
$sql = “SET NAMES ‘utf8′”;
mysql_query($sql, $link);
have you tryed switching the places of the functions?
$jsonrequest = utf8_encode(json_encode($request));
utf8_encode only encodes strings not arrays
You convert the initial request to UTF-8, so I assume it's something else. But when you send the data back, you do not convert it back to the original encoding.
Are you sure you send the data in the encoding expected by the server?
I also use both ZF and utf-8 encoded strings in AJAX calls and I think that the uft8_encode and utf8_decode functions should be obsolete.
Do you have a valid meta tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" / >
and a valid doctype
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
?