Ajax update on div with a id - php

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!

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.
});
}

Ajax Notification system - using latest notification_id

So I have the majority of my system working and I am stuck on one last bit
The GET is currentlyusing the same notification_id it gets from the while loop, so it constantly searches against that id for new records over and over.
LIKE SO...
jquery....4862996 (line 4)
GET http://viewajax.php?notification_id=43&_=1405814864693
jquery....4862996 (line 4)
GET http://viewajax.php?notification_id=43&_=1405814864694
What I'm looking to do is search the first notification_id from the while loop send it off to the server side viewajax.php to see if there is a new record and if there is insert it into its div, (which it currently does) but then use that same new notification_id from the server on its next ajax cycle for new records. I've tried everything and asked many questions and I've been looking high and low online for possible solutions to no avail.
Any help would be greatly appreciated and I will love you forever.
AJAX
<?
$user1_id=$_SESSION['id'];
$call="select * from notifications WHERE notification_targetuser='$user1_id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
function loadIt() {
var notification_id=<?php echo $notification['notification_id'] ;?>
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(data){
$("#notif_actual_text-"+notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
});
}
setInterval(loadIt, 10000);
</script>
<? }}?>
VIEWAJAX.php
if(isset($_GET['notification_id'])){
$id= mysqli_real_escape_string($mysqli,$_GET['notification_id']);
$user1_id= $_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id,notification_content,notification_time,notification_triggeredby from notifications where notification_id > '$id' AND notification_status='1' ");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
$json['notification_triggeredby'] = $resultArr['notification_triggeredby'];
$json['notification_time'] = $resultArr['notification_time'];
mysqli_free_result($com);
echo json_encode($json);
}
EDIT
PHP SOURCE
{"num":0,"notification_id":null,"notification_content":null,"notification_triggeredby":null,"notification_time":null}
AJAX SOURCE
<script type="text/javascript">
function loadIt() {
var notification_id=44
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(data){
$("#notif_actual_text-"+notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
});
}
setInterval(loadIt, 10000);
</script>
Why don't you just update "notification_status" to 0 after you retrieve it in the php parts? Then it will not be retrieved again.

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.

Ajax comments calling json into function

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.

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories