Edit:
Solved using the below suggestion of removing:echo '{"results":'.json_encode($arr).'}';
and replacing with echo json_encode($arr);
This combined with replacing these lines:
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
with
$.each(data, function(key, val) {
$("#chatbox").html(this.number);
});
Made it work, I can now access the object data using the this
followed by the property I want.
End Edit
Hi could anyone help me with these JSON feed. I am almost there with it (I think) however whenever I put this feed into JQuery it is picked us as a string rather than as an array of JSON objects and I can't figure out why.
The PHP to create the feed:
<?php
session_start();
include 'connect.php';
$number = $_SESSION['number'];
$query = "SELECT * FROM $tableName WHERE number='$number'";
$result = mysql_query($query, $sqlCon);
$arr = array();
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
if (count($arr) == 0)
{
echo "Your reference number is: $number";
} else {
echo '{"results":'.json_encode($arr).'}';
}
?>
The returned JSON looks like this:
{"results":[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]}
What I instead want is:
[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]
Or a return value which would allow me to iterate over the objects.
The JQuery I'm reading it with:
$.getJSON('get.php', function(data) {
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
});
I'm guessing my problem is the way in which I'm creating the JSON feed but I'm just stuck and cant figure out how to fix it.
Any help would be appreciated, thanks.