Ajax comments calling json into function - php

I'm working on ajax comments and wondering how I can get the items from the comment_add.php page with the below bit of code so then I can insert it into obj.innerHTML.
function addcomment(streamid,content,containerid,posterid,postername,postid){
var obj = document.getElementById(containerid);
$.post("../comment_add.php", { streamid: streamid,content:content} );
obj.innerHTML = obj.innerHTML + "<div class='stream_comment'><table width='100%'><tbody><tr><td valign='top' width='30px'><img style='border:none;padding:0px;height:30px;width:30px;border-radius:0px;' src='imgs/cropped"+posterid+".jpg' onerror='this.src="img/no_profile_img.jpeg";'></td><td valign='top' align='left'><a href='profile.php?username="+posterid+"'>"+postername+" </a>"+content+"</td></tr></tbody></table></div>";
COMMENT_ADD.PHP
<?php
session_start();
require"include/load.php";
if(isset($_POST['streamid'])&isset($_POST['content'])){
user_core::add_comment($_POST['streamid'],$_POST['content']);
}
$json = array();
$check = "SELECT comment_id,comment_streamitem, comment_content FROM streamdata_comments";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
mysqli_free_result($check1);
$check = "SELECT * FROM users WHERE id=".$_SESSION['id']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
echo json_encode($json);
?>
I did try using this code. Yet everytime I comment, it adds it into the 1st post in the stream only, as where the top function doesn't, it adds it into the status the user comments on.
<script>
$(document).ready(function(){
$("form#mycommentform").submit(function(event) {
event.preventDefault();
var streamid = $("#streamid").val();
var content = $(this).children('#content').val();
$.ajax({
type: "POST",
url: "comment_add.php",
cache: false,
dataType: "json",
data: { 'streamid': streamid, 'content': content},
success: function(html){
$("#commentaddid").html("<div class='stream_comment_holder' id='comment_holder_"+html['comment_streamitem']+"'><div id='comment_list_"+html['comment_streamitem']+"'><div class='stream_comment' id='comment_"+html['comment_id']+"'>div class='stream_comment_holder' id= style='display:;'><div class='stream_comment'><table width='100%'><tbody><tr><td valign='top' width='30px'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+html['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></td><td valign='top' align='left'><a href='profile.php?username="+html['username']+"'>"+html['first']+" </a>"+html['comment_content']+"</td></tr></tbody></table></div></div></div></div>");
}
});
return false
});
});
</script>

It looks like the top function gets passed a containerId which it uses to know where to put the comment. However, the lower ajax version always puts the comment into #commentaddid.
It is not clear where in the DOM you want the comment to appear, but wherever it is you will need to replace the #commentaddid selector with it's selector.

Related

Browsing inside Ajax response

I'm new to jquery & Ajax.
I have a php file with jquery inside it, which loads content from another php file on selection of a date
$("#datepicker3").change(function(){
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
}
});
});
The issue I'm facing is contents in ptreport1.php has links (pagination) contained to browsing scope of that php file. When the user clicks on those links he is directed out of the original page ajax content is loaded from.
Is there anyway to prevent that and load content in original page.
Update # 2.
After ediding the codes with preventDefault, following is my jquery
<script>
$(document).ready(function() {
$("#searchr").hide();
$(function() {
$('#datepicker3' ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd M yy'
});
});
$("#datepicker3").change(function(){
var myValue = $(this).val();
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
var page = $("#pagediv").html();
var timestamp =$("#timediv").html();
var dataString = 'page='+ page + '&timestamp='+ timestamp;
$.ajax({
type: "GET",
url: "ptreport1.php",
data: dataString,
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
}
});
});
}
});
});
});
</script>
and ptreport1.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include "core.php";
connectdb();
$page = $_GET['page'];
$timestamp = $_GET['timestamp'];
$ptdate = $_POST['ptdate'];
if(isset($timestamp)){
$ptdate = date('d M Y', $_GET['timestamp']);
}else{
$timestamp = strtotime($ptdate);
}
if(!isset($page)){
$page=1;
}
if($page=="" || $page<=0)$page=1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."'")or die("error querying");
$numrows = mysqli_num_rows($numresults);
$num_items = $numrows; //changable
$items_per_page= 5;
$num_pages = ceil($num_items/$items_per_page);
if($page>$num_pages)$page= $num_pages;
$limit_start = ($page-1)*$items_per_page;
$npage = $page+1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."' LIMIT $limit_start, $items_per_page")or die("error querying");
$numrows = mysqli_num_rows($numresults);
if($numrows==0){
echo "Sorry, No results for $ptdate.";
exit();
}
echo "<p><table>";
while($msdrow = mysqli_fetch_assoc($numresults)){
$charge= $msdrow['charge'];
$fname= $msdrow['firstname'];
$lname= $msdrow['lastname'];
// $fullname = $fname." ".$lname;
echo "<tr><td>$fname</td><td>$lname</td><td>$charge</td></tr>";
$totalcharge = $totalcharge+$charge;
}
echo "<b><tr><td colspan=\"2\">Total Charge</td><td>$totalcharge</td></tr></b></table></p>";
echo "<div id='pagediv' >";
echo "$page</div>";
echo "<div id='timediv' >";
echo "$timestamp</div>";
echo "<p align=\"center\">";
if($page>1)
{
$ppage = $page-1;
echo "«PREV ";
}
if($page<$num_pages)
{
$npage = $page+1;
echo "Next»";
}
echo "<br/>$page/$num_pages<br/>";
echo "</p>";
What am i doing wrong here, since it after second click it jumps out of ajax directs to original php page.
Thanx
You would need to set onclick event handlers on the pagination links after loading the content in ptreport1.php. You'll need to change .pagination-link to match the links in the content you are loading.
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
});
}

Keep Ajax alive

I'm trying to get my ajax to request information from the server and also keep it alive for at least 1 minuite before having a break and restarting and getting and passing a new streamitem_id if their were one inserted since the last call.
Currently it runs so fast and only once and I don't understand why.
AJAX
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
setTimeout("wait()",1000);
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
wait();
});
</script>
PHP
if (isset($_POST['streamitem_id'])) {
$lastID = (int)$_POST['streamitem_id'];
if(empty($lastID)) {
die('timeout');
}
else {
$following_string = $_SESSION['id'];
$result="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE d.streamitem_id > '$lastID'
AND c.comment_poster = '$following_string'
AND (d.streamitem_creator = '$following_string')
OR d.streamitem_creator IN $friendlist
AND d.streamitem_type_id NOT IN ('3')
ORDER BY '$lastID' DESC LIMIT 1";
$result = mysqli_query($mysqli, $result) or die(mysqli_error($mysqli));
while ($resultArr = mysqli_fetch_array($result)) {
$json = array();
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
echo json_encode($json);
}}}
setTimeout does not work like you expect. An ajax-request can't be "kept alive" like you want. The request is sent, the PHP-script returns the content and the ajax-script get's the result. All this happens within ~1-2 seconds.
If this is used for some sort of stream (as it looks like), you would have to make the function repeat itself again and again over a small interval.
I've changed your code like this:
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
setInterval(wait,10000);
});
</script>
The ajax-script will fire every 10 seconds. You can edit the speed yourself, but keep in mind that too many requests in a short timeperiod can make your server crash/go slow.
In your PHP script, you'll need to use the sleep function in order to keep your connection alive.
Something like:
function callScript(callback) {
$.post('myscript.php',{data:data},function(data) {
if (data == -1) {
return callScript(callback);
}
return callback(data);
}
}
myscript.php
$interval = 50;
$iters = floor(1000 / $interval);
while($conditional === false) {
if (--$iters < 1) { die(-1); }
sleep($interval);
}
echo $json;
While this isn't exactly what you need, it can easily be adapted to what you need. I've done this with other stuff, while costly, you can use a sql statements to wait for entries to be added etc.

jQuery.ajax File Delete

I have a jquery delete statement and it's only deleting the NEWEST upload on my files (using mysql) Say I had "file uploaded first", "file uploaded second", "file uploaded last(newest file)". If I click "file uploaded first or second", it deletes the newest (file uploaded third).
$(document).on('click', '.del', function(){
var sid = $(this).next('.hiddenVid').val();
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
this is your error ->
var sid = "$vid";.
It will only produce the ID for the latest item that you put in.
Add an item to your echo statement so you can reference it later in the click function.
Add a reference to the vid in a hidden input.
Change this
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
To this:
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button><input type='hidden' class='hiddenVid' value='".$vid."'/></td>";
Change your click function to reference the real sid now.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
});
If you want to return the rows after the update, you'll need to spit the data back to be printed, based on the above method you use to retrieve the rows and return them, you could reuse it.
$id = mysql_real_escape_string($_REQUEST['id']);
$DB->Query("DELETE FROM `files` WHERE `id`='$id'");
if(TRUE == (unlink("uploads/$id")):
$DB->Query("SELECT * FROM `files` WHERE `author`='$username'");
$file = $DB->Get();
$obj = new stdClass();
$i = 0;
foreach($file as $key => $value){
$n = $value['name'];
$vid = $value['id'];
$date = "<td>".$value['date']."</td>";
$fname = "<td><a id='$vid' href='download.php?id=$vid'>$n</a></td>";
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
$size = "<td>".filesize("uploads/".$vid."/".$value['name'])." bytes</td>";
$obj->$i = $files = "<tr>".$fname.$size.$date.$option."</tr>";
$i++;
}
echo json_encode($obj);
endif;
Now we need to change the click handler to expect a dataType and replace the existing data in the table.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
dataType: 'json',
data: {id:sid},
success: function(data){
$('table').empty();
$.each(data, function(i,obj){
$('table').append(obj);
}
}
});
return false;
});
});

Ajax/Php get more than 1 result

I've built up a script that is to get users posts from a database, and I'm almost there. The ajax calls and I get the 10 posts in the response in Firebug, only it shows only 1 post in the page when I click load more. What do I need to add to the code below to show 9 more results?
AJAX
<script type="text/javascript">
$(document).ready(function(){
$('.load_more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#load"+ID).html('Loading...');
$.ajax({
type: "POST",
url: "include/load_more_home_posts.php",
cache: false,
dataType: "json",
data: { streamitem_id: ID},
cache: false,
success: function(stream){
$("#articles").prepend("<div id='divider-"+stream['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+stream['username']+"'>"+stream['first']+" "+ stream['middle']+" "+stream['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+stream['streamitem_timestamp']+"</a><hr>"+stream['streamitem_content']+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+stream['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+stream['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a title='Like "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' id='likecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+stream['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'>Like</a></div><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'><a title='See who likes "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' href='include/likes.php?streamitem_id="+stream['streamitem_id']+"' /></a></div></div></form></div><div id='streamdislike'><a id='dislikecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+stream['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'>Dislike</a></div><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'></div></div></form><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+stream['streamitem_id']+"'><div id='comment_list_"+stream['streamitem_id']+"'></div><div class='stream_comment_inputarea'><form id='mycommentform' method='POST' class='form_statusinput'>\
<input type='hidden' name='streamidcontent' id='streamidcontent' value='"+stream['streamitem_id']+"'>\
<input type='input' name='commentingcontents' id='commentingcontents' placeholder='Say something' autocomplete='off'>\
<input type='submit' id='button' value='Feed'><br/></div></div>");
// remove the previous load more link
$("#load"+ID).remove();
}
});
}
return false;
});
});
</script>
include/load_more_home_posts.php
<?php
session_start();
include("rawfeeds_load.php");
if (isset($_POST['streamitem_id']) && $_POST['streamitem_id'] != "") {
$lastID = mysqli_real_escape_string($mysqli,$_POST['streamitem_id']);
$json= array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string')
ORDER BY d.streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streams'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['streamdata'][] = $json;
}
echo json_encode($json);
}
?>
You recive from PHP an JSON like [{item1, item2},{item11, item12},...] and without iterate over it you are using only first group. I think the best and the easiest way will be using $.getJSON function instead of $.ajax. Look here at the second example, I think it is all you need to handle JSON received from PHP.

Ajax update on div with a id

How would I go about updating a div with a id every x seconds? I want it to update the users statuses which are contained inside this, that includes the time the amount of comments made on that individual post.
I've tried setInterval but it takes 10 seconds for the status to be added and then duplicates the status every x amounts of seconds after that. All I need is for the response data to be updated not the insertion of the comment to be re-added every 10 seconds.
HTML:
<div id='divider-"+response['streamitem_id']+'></div>
JavaScript:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg },
success: function(response){
$("#homestatusid").html("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+newmsg+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</div></a><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'></div></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</div></a><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></div><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'><table width=100%><tr><td valign=top width=30px><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><td valign=top align=left><div class='stream_comment_inputarea'><input id='addcomment' type='text' name='content' style='width:100%;' class='input_comment' placeholder='Write a comment...' onkeyup='growcommentinput(this);' autocomplete='off' onkeypress=\"if(event.keyCode==13){addcomment("+response['streamitem_id']+",this.value,'comment_list_"+response['streamitem_id']+"',"+response['id']+",'"+response['first']+" "+ response['middle']+" "+response['last']+"');this.value='';}\"><br/></div></div>");
}
});
return false
});
});
INSERT.PHP
$json = array();
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_id DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];
mysql_free_result($check1);
$check = "SELECT streamitem_timestamp FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_timestamp DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
mysql_free_result($check1);
$check = "SELECT username, id, first, middle, last FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysql_free_result($check1);
echo json_encode($json);
First wrap up the Ajax call in a single-execution function, with the callback function referring to the same:
$(function() {
(function ajaxcall() {
$.ajax({
url: 'foo.php',
data: {boo:'moo',goo:'loo'},
timeout: function() { ajaxcall(); },
success: function(data) {
//do somethng with the data
//done, now call the function again:
ajaxcall();
}
});
}());
});
Then in the PHP write something like:
$timeout = 30;
$pollinterval = .5;
$counter = 30;
while ($counter >= 0) {
//function which fetches fresh data and sets $test to true if data is returned
list($test,$dataarray) = fetchdata();
if ($test) { //JSON_encode the data array and send it
echo JSON_ENCODE($dataarray);
}
else { //no fresh data, query the db again after wating for some time)
usleep($pollinterval*1000);
$counter -= $pollinterval;
}
//timeout, return whetever you have!
echo JSON_ENCODE($dataarray);
You can use setInterval (see Documentation) or setTimeout (see Documentation).
Sounds like polling. You can include an AJAX call, that will send a request to a backend PHP script that will search the database for further update. if found, it will immediately return the new result. The client side JS on receiving the new data, will wait for say 30 seconds before making another request. If the PHP doesn't find any new data, then it will query the DB again, say after 5 seconds, and continue to do so until a script-defined timeout, say 25 seconds, occur. Then it will return an empty result, on receiving which the client side JS will immediately make another request.
I think this is what you're wanting, using Jquery:
HTML:
<div id="divider-whatever"></div>
Jquery:
$(document).ready(function() {
setInterval(function() {
div = $("#divider-whatever");
$.get(data.php, function(responseData) {
div.html(responseData);
}, 1000);
// change 1000 to whatever time you need
// change data.php to the file where your data is coming from
});
});
*not tested
Hope this helps!

Categories