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.
Related
Im using CKEditor to store HTML input. Its working fine the one way. Data goes into the database exactly as I input it.
However, when I try to retrieve it in JSON, I get all sorts of parsing errors.
Here is a simple string which screws up
<p>This is my text</p>
<span style="font-size:14px">More test</span>
The JSON gets hung up on the double quotes, and the spaces. So I implemented this function in PHP before it gets inserted.
function parseline($string){
$string = str_replace(chr(10), "//n", $string);
$string = str_replace(chr(13), "//n", $string);
$string = str_replace(chr(34), "'", $string);
$string = str_replace("'","\'", $string);
return $string;
}
That line then becomes
<p>This is a test and more content</p>//n<span style=\'font-size:72px\'>
However. This still hangs up the JSON parsing.
How do I correctly store data from CKEditor, and then how to parse it back from the database, so that it can be parsed correctly as JSON??
Ideally I want to store it properly. And then I'll need to reverse parse the //n out to display back in the editor properly. Because right now, if I get valid data, I still get the //n displayed in the editor as actual values.
Ive been on this for 6 hours now. And Im tearing my hair out.
EDIT - Still stuck on this 22 hours later
Here is what is going into the database
<p>qweqweqweqwe</p>
And then Im getting it like this (using Lumen/laravel)
$post = Post::find($id);
return json_encode($post);
Then in Vue Im getting that json
el:'#app',
data : {
post: {}
},
methods: {
getPost: function(id){
var that = this;
$.ajax({
url:'post/'+id,
dataType:'json',
type:'GET'
}).done(function(data){
// Assign the data to Vue
that.post = JSON.parse(data);
}).fail(function(xhr){
});
}
}
This fails, with this exception
Uncaught SyntaxError: Unexpected token
in JSON at position 175
And the json returned is
{"uuid":"0bcb9c59-19da-4dcf-90d6-6dd53adfb449","title":"test","slug":"test","body":"<p>qweqweqweqwe</p>
","created_at":1519529598,"updated_at":1519534639}
So obviously its failing because there is an Enter key after the ending < /p >. But I already tried removing all enter keys and all that before storing. Replacing with new line /n. That works, but then I get //n back, and also things like style="font-size:14px;" from CKeditor, also make it fail, because of the double quotes.
So the issue is. Im storing the data exactly as its entered in the database. Retrieving it properly is just most definitely not working or easy to do at all it seems. At least as valid json.
EDIT 3 - Completeley lost and officially stumped
Im getting this back as json
var data = {
"uuid": "2cd2d954-233a-46d6-8111-29596262d3bc",
"body": "<p>test<\/p>\n",
"cover_img": "https:\/\/static.pexels.com\/photos\/170811\/pexels-photo-170811.jpeg",
"title": "asdf",
"slug": "asdf",
"created_at": 1519536364,
"updated_at": 1519538302
}
If i do
JSON.parse(data);
I consistently get
Uncaught SyntaxError: Unexpected token
in JSON at position 66
Even though if you copy that exact object over to JSONLint.com, its completely valid. Im so stumped. The most stumped I think I have ever been on any issue in my entire career. Which is wierd, because it seems like it would be such an easy bug to find.
Store it directly as HTML in the database. Don't modify, tweak, or otherwise screw with it at all - what's in the database should be exactly what the user submitted. (Stuff like XSS protection, parsing short codes, etc. should be done on display, so you can adjust your algorithms while still having the original HTML to work with.)
Provide it to Vue by running it through json_encode, which will escape it correctly:
$response = ['html' => $html];
return json_encode($response);
(You can also just do json_encode($html), which will return a JS-friendly string instead of a JSON object. Vue'll be happy with that, too.)
The resulting JSON will be:
{"html":"<p>This is my text<\/p>\n\n<span style=\"font-size:14px\">More test<\/span>"}
which Vue will be just fine with when you JSON.parse it.
Assuming a CKEditor instance named editor1, get CKEditor data, construct an object with it, stringify it and send it to database without PHP manipulation (JSON.stringify will take care of escaping characters):
JSON.stringify({'ckdata': editor1.getData()})
Retrieve data from database as text without PHP manipulation and parse it as JSON object:
JSON.parse(databasedata).ckdata;
EDIT: ceejayoz gave a better answer, since data is stored unmodified in database
I am trying to pass JSON object from angular to php like this :
<?php
$placeBean = "{{masterCtrl.getLastplace();}}";
//VAR DUMP IS -> string(30) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
$json = '{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}';
//VAR DUMP IS -> string(70) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
?>
Then I need to parse the json in $placeBean, because it is not yet a json in php, so I use
<?php
$manage = json_decode($placeBean);
?>
And this is the problem... because it doesn't work, in fact the result is an empty value: instead, if I do the same thing with $json( instead of $placeBean), the code works perfectly.
I Think the issue is some
missing chars, which are placed in$json, and not in $placeBean.
Those are the echo of the variables
ECHO OF JSON ->{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
ECHO OF placeBean ->
placeBean{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
I Also tried to use json_last_error, which gave me this : - Syntax error, malformed
Well, the first one is not a valid JSON object, for this PHP refuses to parse it.
When you run it though AngularJS it will actually use its own mechanism and replaces the string with the data returned by the masterCtrl.getLastplace() call.
I am using .ajax() to send a request to the server. The server is using PHP to process the request.
According to php urldecode, $_REQUEST is already decoded and Plus symbols ('+') are decoded to a space character.
What I have found is that Plus symbols are being decoded to a underscore ('_'). This is true for both + and %20. Is there any way around this? This seems like unexpected behavior.
Code sample for what its worth:
ajax:
$.ajax({
url: 'mySite.php',
method: 'POST',
data: $(this).serialize()
});
php:
$myVar = "Veh #";
if (isset($_REQUEST["$myVar"])){
//do stuff
}
//to see request
var_dump($_REQUEST);
The var_dump gives
array(1) {["Veh_#"]=> string(1) "6"}
I would expect is to be
array(1) {["Veh #"]=> string(1) "6"}
fiddler data posted:
Veh+%23=6
I may be incorrect as I'm still learning PHP, but I think this is standard behaviour when using GET and POST in PHP.
see here in the documentation
http://www.php.net/manual/en/language.variables.external.php
I not aware of anyway around this.
also see this stack overflow question
Get PHP to stop replacing '.' characters in $_GET or $_POST arrays?
Note:
Dots and spaces in variable names are converted to underscores.
(php.net - external variables)
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!
I am building a request in Flash that contains a JSON encoded Array of Objects. This is encoded using as3corelib. The request is then passed to JavaScript via ExternalInterface and a jquery ajax call sends the request off to the server.
In PHP, the incoming data is parsed, but the json_decode returns null, giving a Malformed JSON error. var_dump results in comments:
<?php
(isset($_POST['gdata']) && !empty($_POST['gdata'])) ? $gamedata = $_POST['gdata'] : returnError("game data not specified");
var_dump($gamedata); // (String) = string(37) "[{\"duration\":1,\"id\":\"game2\"}]"
$gamedata = json_decode(utf8_encode(trim($gamedata)),true);
var_dump($gamedata); // null
$gamedata = json_decode("[{\"duration\":1,\"id\":\"game2\"}]",true);
var_dump($gamedata);
/*
array(1) {
[0]=>
object(stdClass)#1 (2) {
["duration"]=>
int(1)
["id"]=>
string(7) "game2"
}
}
*/
?>
What I don't understand is that attempting to decode the variable returns null, but the same text decoded from a literal string works fine. What can I do to clean up the incoming data and make it readable for json_decode?
Edit: php_info() says that magic_quotes_gpc is enabled. Could that be the issue?
magic_quotes_gpc could be the issue, yes. And if you re-encode blindly w/o knowing the charset could be an issue as well.
So if you know magic_quotes_gpc is enabled, you need to strip slashes first.
For the charset, take care you know in which charset the incomming data is encoded, not that it's already utf-8 encoded and you assume it's latin-1 and convert it again.