I have been trying to basically create a div for each row of the json list returned via ajax which would append to the main div #chatcontents. However, i am facing problems with the correct syntax. I think the error is how my json is being returned.
This is the function which does the ajax call in the index.php
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
success: function (json) {
if(json)
{
for (var i = 0, len = json.length; i < len; ++i) {
var results = json[i];
var newDiv = $("<div>" + results.1 + results.2 "</div>");
}
$('#chatContents').append(newDiv);
}
}
});
}
thread.php returns a Json result like this..
[{"0":"something","1":"41234","2":"test"},
{"0":"somethingmore","1":"2131","2":"test2"}]
The codes i have seen online seem to return the key but mine are in numberics (0,1,2). I think its coz of the way i have the returned the array. It is a 2d array which was converted to JSON. I am not sure if this is causing the problem as to how i loop through the array in the first page. Any help would be appreciated.
For a clearer pic:
thread.php has this code:
<META HTTP-EQUIV="Refresh" CONTENT="3">
<?php
$latestmsgs = retrieveNewMsgs($lastpost,$currtime);
?>
<?php echo json_encode($latestmsgs);?>
So basically, thread.php is refreshing every 3 seconds. Index.php makes an ajax call to this page and retrieves the latest msg in the form of json and appends.
I hope its clearer.
I think
results.1is invalid syntax, you should useresults[1].EDIT
You have syntax errors on this line (apart from the bracket syntax instead of dots, you are missing a plus sign):
It should be
Make sure your callback is getting a parsed JSON object, not a raw JSON string. Alert
typeof jsoninside the callback, it should say “object”. If it says “string”, adddataType: 'json'to the options object passed to$.ajax, and/or make sure the server is setting the proper content-type for the response.Once you fix that, your code should work. See this jsfiddle.
EDIT 2
The line with
.appendshould be inside of yourforloop, otherwise only the last result on the JSON will be appended to the div. See updated fiddle.You said on the comments: “I am appending to a class=”container” div”. But your code says you’re appending to a div with ID == “chatContents”. Do you have such div?
When you say an alert stopped working, it means there is probably some error before the alert preventing the rest of the script to execute. Check Firebug’s console for errors, and double-check all code before the alert.