I am ‘echoing’ a json array back to ajax, but it is printing the entire array to the screen. I am at my wits end! Can someone see anything wrong with the following code that would cause this?
My ajax call:
theUrl = 'myphpquerypage.php?id=somenumber'
$.getJSON(theUrl, function(data) {
var content = "";
$.each(data, function(index, array) {
content += "<div>" + array.filename + "</div>";
$(content).appendTo('#myContentDivTag');
myphpquerypage.php:
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['id'])) {
$stmt = $pdo->prepare("call getimages(?)");
$stmt->execute(array($_GET['id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
The echo is causing this to go directly to the screen (nothing shows up in #myContentDivTag):
[{"filename":"img4dc458200caa7.jpg"},{"filename":"img41b65171bd651.jpg"}, {"filename":"img41be6c0eae1a4.jpg"},{"filename":"img41e5d5eede9da.jpg"}, {"filename":"img41e5d64383039.jpg"},{"filename":"img422fb82b3768a.jpg"}, {"filename":"img422fc528cc8d1.jpg"}]
Thanks everyone, any help would be greatly appreciated. I have spent hours trying different things. Obviously I am getting the json encoded array back, but I cannot get it to properly display.
I suppose we have different ways of dealing with JSON data in ajax requests, and though yours isn’t wrong, mine seems to work 😉
Here is an example of how I’d do it, seems to work fine:http://jsfiddle.net/5YWpr/3/
(Note, it uses jsfiddle’s ajax tester, so it posts sample json data to be returned, why the ajax request looks weird, use the one in this thread if you just want to insert the code).
Javascript:
HTML:
Tell me how it goes.