On the first page I have this function:
<script>
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
dataType: 'json',
data: latestid,
url: '2includejson.php?lastid='+ latestid + '',
timeout: 4000,
success: function(data) {
$("#cont_div").html(data);
$("#cont_div").clone().prependTo($("#newdiv"));
$("#notice_div").html('');
$("#cont_div").html('');
window.setTimeout(update, 4000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
</script>
And some php.
The included file:
<?
header("Content-Type: application/json", true);
$la = $_GET['lastid'];
include ("../../setup.php");
$jsonArray[] = array();
$count = 1; // first message is the newest on load
$get = $DB->query("SELECT * FROM board WHERE id>'$la' ORDER BY id DESC LIMIT 5", __FILE__, __LINE__);
while ($msg = $DB->fetch_array($get))
{
if($count == 1){
$latestid = $msg['id']; // newest message - this I need to pass to the other page
}
$count++;
$jsonArray = "$msg[msg]";
}
echo json_encode($jsonArray);
?>
I’m just trying to learn how to use ajax and jquery.
As you see, I pass latestid as js variable through the URL
url: ‘2includejson.php?lastid=’+ latestid + ”,
I need to renew/post pack a newer value from the included page but I have no idea how to do so. Before using json I could just overwrite it with javascript, but now I don’t know… The newer value will then be posted again as latestid.
You can declare the array without
[]:Also you should then append the data to the array instead of making a string:
And in the end:
Then in JavaScript, you should declare
latestid:And inside the ajax function, you should just pass the data as an object, and not twice like you’re doing now. And just replace
latestidthere, which has been returned in JSON format: