Hello I'm working on a shoutbox and I need help with auto updating them via ajax.
Here is my shoutbox with ?getShouts=true at the end:
Here is my shoutbox without that:
My goal here is to run a web request and get the contents of the shoutbox in ?getShouts and update on the page I'm in.
This PHP code is run on the top of the page:
if(!empty($_GET['getShouts']))
{
$sbinfo = "";
$rows = $db->query("SELECT * FROM shouts order by shoutid DESC limit 20");
while($row = $rows->fetch_array(MYSQL_ASSOC))
$sbinfo .= $row['username'] . ": " . $row['shout'] . "<br />";
}
That stores the markup for the text into one string.
later in php file it displays the markup by: if(!empty($_GET['getShouts'])) echo $markup;
Here is my ajax I'm currently running:
<script>
$(document).ready(function() {
getMessages();
});
function getMessages()
{
//make request
var req = new XMLHttpRequest();
req.open("GET", location.href+"?getShouts=true", true);
req.send(null);
document.getElementById("shouts-box").innerHTML = req.responseXML.getElementsById("shouts-box")[0].innerHTML;
//loop
window.setInterval(getMessages,3000);
}
</script>
any ideas?
I have found a solution for this using:
$('#div').load('index.php?getShouts=true #div');