I create a huge JSON-Object and save it in my database. But when I load the “string” and echo it in PHP, I can’t access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with “echo json_encode($arr);” it works fine, but I need to save the Object for caching).
{“247”:{“0″:”This is a
question”,”1″:””,”2″:”247″,”3″:”0″,”answers”:[[“Answer1″,”960″,”1”],[“Answer
2″,”962″,”0”],[“Answer
3″,”961″,”0”],[“Answer
4″,”963″,”0”]]},{“248”:{“0″:”This is a
question”,”1″:””,”2″:”247″,”3″:”0″,”answers”:[[“Answer1″,”960″,”1”],[“Answer
2″,”962″,”0”],[“Answer
3″,”961″,”0”],[“Answer
4″,”963″,”0”]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn’t work.
Update 1: forget to tell that I’m using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert “This is a question”
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I’d suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you’ve done that, if you still can’t spot the problem, try this code:
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
Hope that helps!