I am having trouble with loading JSON into an app that im creating
$("#load_basic").click(function(){
$.ajax({
url: 'php/show.php',
method: 'get',
dataType: 'json',
success: function(json) {
$("#textarea").html(json.doc);
}
});
});
My JSON from show.php is as follows
{
"id": "1",
"title": "doc 1",
"doc": "Lorem Ipsum",
"lastsaved": "2012-02-12 08:33:49"
} {
"id": "3",
"title": "doc 2",
"doc": "another lorem ipsum document",
"lastsaved": "2012-02-12 08:39:31"
}
Please can anyone help. Firstly I was attempting to do it locally and I thought this might be the problem but now Ive tried it live on the server and still no joy. Any ideas?
This is the show.php source for creating the JSON file
<?php
header('Content-type: application/json');
include 'db.php';
$query = 'SELECT * FROM docs';
$result = mysql_query($query) or die('<p class="db_error"><b>A fatal MySQL error occurred while trying to select <b>EVERYTHING</b> from the database.</b><br />Query: '.$query.'<br />Error: ('.mysql_errno().') '.mysql_error().'</p>');
while ($row = mysql_fetch_assoc($result)) {
$arr = array('id'=>$row['id'],'title'=>$row['title'],'doc'=>$row['doc'],'lastsaved'=>$lastsaved = $row['lastsaved']);
echo json_encode($arr);
}//end while
?>
The JSON which you have uploaded is not valid JSON. What I think you have expected is array of JSON, looking like following.
Notice existence of square brackets and commas. To get output like this, use
json_encode()on array of objects (or associative arrays, depending on what you’re using), instead of echoing every separately. For example instead of:Do:
If you have a lot of data which might not fit into memory as single array, you can try:
[character,character unless it’s first object]character