I'm so frustrated with this.
I'm using Angular from CDN and I'm calling a $http.get request to a PHP file that prints all the result set (mysql) in JSON format, which is "well done".
But, I have stored some backslashes into the database as part of the value of a field. E.G:
{"Field 1":"user1"},{"Field 2":"some_data\2"}
That crashes the entire page and the data in the view is not being displayed. It's printed in the raw JSON file this way:
{"Field 2":"some_data�2"}
Currently I'm printing the resultant json "manually":
$outp = '{"Field 2":"'.$resultset['field_data'].'"}';
echo $outp;
I've tried everything I know: addslashes(), stripslashes(), htmlspecialchars(), json_encode()... Error is:
SyntaxError: Unexpected token in JSON at position 138742
Can anyone help me, please?
Related
I am having a weird issue, when i use json_decode() on some json from a jquery ajax call it's coming back always saying that the json is malformed (JSON_ERROR_SYNTAX).
I say this is weird because if i take a copy of the raw posted json from the developer console and manually push it through json_decode() then it decodes perfectly fine.
I have uploaded a txt file of the example json here : https://drive.google.com/file/d/1IZ5RkpFK7KLUNYeZe4dPdxGWZXinmFSJ/view?usp=sharing which works manually parsing it but not from posted data. Another weird issue is if i save the json string to a longtext field in a mysql database and then pull it out again, it then decodes fine; but this isn't ideal, it needs to validate it before going to the database and i'm unsure why this would allow it to decode anyway.
Any ideas?
This might be happeing due to new line code added in your code. You can add below code and try to decode the code again it might work.
$content = preg_replace('/[\r\n\t\s]+/s', ' ', $content);#new lines, multiple spaces/tabs/newlines
$content = preg_replace('#/\*.*?\*/#', '', $content);#comments
$content = preg_replace('/^\s+/', '', $content);#spaces on the begining
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 want to use json_decode() to decode a string stored in a database like this:
{"results":[{"r":"1","c":"0"},{"r":"2","c":"0"},{"r":"3","c":"0"}]}
The problem is: the function returns NULL.
But when I try the following code, everything works:
$data ='{"results":[{"r":"1","c":"0"},{"r":"2","c":"0"},{"r":"3","c":"0"}]}';
$JO=json_decode($data);
var_dump($JO);
The value returned from the database is exactly the same as I described above.
For all the people who might get the same problem, my problem was that when I was getting data from database to display it, I was adding html style and table parameters to the data, after removing them everything went back to normal.
I creating an app in which I'm using php in server side.When an Ajax call is made its calling an php to retrieve the data from the table but the issue is some table contains html & special characters tags so i get an error in the Ajax :
05-31 00:59:07.670: D/CordovaLog(872): Server is not responding... Please try again: SyntaxError: Unexpected token <
05-31 00:59:07.670: I/chromium(872): [INFO:CONSOLE(342)] "Server is not responding... Please try again: SyntaxError: Unexpected token <", source: file:///android_asset/www/home.html (342)
can any tell how to solve this issue.
Thanks in advance.
you may use escapeHtml which Returns an HTML escaped representation of the given plain text.
For more info see at escapeHtml
Or you may use TextUtils.htmlEncode("your json tag") to encode html.
Edit
As you are using phonegap so you may use htmlencoding is PHP also as
htmlentities($str, ENT_QUOTES);
For more information see at htmlentities in PHP
To encode html in php and decode back in your app,you may refer this link
Using PHP’s JSON encode and decode functions to handle data sent to and from your app
I'm moving php code from one linux server to another, and the new one is producing rubbish.
In Firebug, the first result looks great, like normal json encoded values, and works.
The second result (new server) is preceded by "html" and "body" tags, a "p" tag, and then "quot;" instead of actual quotes around the data (sorry, I couldn't get the form to display all that), and throws an error.
In both cases, the code is the same, the output an array passed through json_encode.
Could this be a configuration error?
Thanks in advance.
John
Well, ultimately I added header('Content-type: application/json'); which removed the encoded html. I'd sure like to know why I had to do that.