long polling doesn't stop - php

I tried to modified the long polling code to fit my situation.
I would like to count the total number from mysql and if the number changes (increase or decrease), it will notify me.
The problem is the while loop keep looping. How can I stop it? I just need to have notification whenever the total sum change.
<?php
include("db.php");
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$old_totalsum = $row['totalsum'];
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var old_totalsum =<?php echo $old_totalsum; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_totalsum=" + old_totalsum,
async: true,
cache: false,
success: function(data){
var json = "eval(+(" + data + ")+)";
if(json['msg'] != "") {
alert(data);
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
}); // end ajax
} //end waitformsg
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
<----------------------------------------------------------->
poll.php
<----------------------------------------------------------->
<?php
include("db.php");
$old_totalsum = $_GET['old_totalsum'];
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
}
while($last_sum < $old_totalsum || $last_sum > $old_totalsum)
while($last_sum <= $old_totalsum)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
//echo $last_sum;
//return;
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_sum;
echo json_encode($response);
?>
<------------------------------------------->

I expected logic like this:
$latest_sum= -1;
// Loop until sum from DB is different from what was passed in
while( $latest_sum == -1 || $latest_sum!= $old_sum ){
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$lastest_sum = $row['totalsum'];
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $latest_sum;
echo json_encode($response);
If it takes a long time to change, then Apache (or whatever is running PHP) will likely cancel the request. This is also going to run lots of queries on the db which is expensive.
So it would be better to have your loop in the javascript. It would call a function that would just return the latest sum from the database. The javascript should wait a second or more inbetween each request.
If performance is still too hard on the database, then the php should somehow cache the value every minute and return the cached value.

Related

Sometimes ajax database call return empty array?

I am trying to figure out why sometimes my php function returns an empty array. The event to trigger the ajax call is when a drop down is changed and it then hits my php function. Most of the time it returns the data from the database, but sometimes it doesn't, despite doing the exact same thing (changing the drop down) Any ideas on what can cause this? Basically I am using the console.log to check what is being returned and sometimes, nothing is. Despite other times with the same inputs it working just fine.
$(document).ready(function() {
$( "#qtrselect" ).change(function() {
qtrselection = $( "#qtrselect" ).val();
createQtrTable(qtrselection);
$('#qtrselect').prop('disabled', true);
setTimeout(function () {
$('#qtrselect').prop('disabled', false);
}, 1000);
});
} );
function createQtrTable(qtrselection, id) {
$.ajax({
type : 'POST',
url : 'createnewtable.php',
data : {qtrdate: qtrselection, id: id},
success : function(response)
{
response = jQuery.parseJSON(response);
totalcommision = 0;
totalpayments = 0;
for (i = 0; i < response.length; i++) {
totalcommision += parseFloat(response[i][0]);
totalpayments += parseFloat(response[i][3]);
}
//I've cut out a bit here as it's not really needed to see the problem.
}
});
}
createnewtable.php
$qtrdate = $_POST['qtrdate'];
$id = $_POST['id'];
$startdate = '';
$enddate = '';
switch ($qtrdate) {
case 0:
$startdate = '2016-01-01' ;
$enddate = '2018-12-30';
break;
case 1:
$startdate = '2016-08-01' ;
$enddate = '2016-10-31';
break;
case 2:
$startdate = '2016-11-01' ;
$enddate = '2017-01-31';
break;
case 3:
$startdate = '2017-02-01' ;
$enddate = '2017-04-30';
break;
case 4:
$startdate = '2017-05-01' ;
$enddate = '2017-07-31';
break;
}
try
{
$stmt = $db_con->prepare("SELECT com.commisionAmount, stu.studentName, pay.paymentDate, pay.paymentAmount FROM `commisions` as com INNER JOIN `accounts` as acc ON com.commisionAccount = acc.id INNER JOIN `studentpayments` as pay ON com.paymentID = pay.id INNER JOIN `students` as stu ON pay.paymentStudent = stu.id WHERE pay.paymentDate BETWEEN '$startdate' AND '$enddate' AND acc.id = '$id'");
$stmt->execute();
$results = $stmt->fetchAll();
$results = json_encode($results);
echo $results;
}
catch(PDOException $e){
echo $e->getMessage();
}
Thanks.
Your id variable in javascript is always undefined.
In this line:
createQtrTable(qtrselection);
you need id
createQtrTable(qtrselection, id);

BootstrapTable, No matching records found

For a few days I am busy solving following. I would like to load bootstrap table through a click into a <div>. My situation:
index.php
<div id="page-content">
<div id="data" class="animated"></div> on page load, loaddata
<div id="table" class="animated">
<table id="report-table" data-toggle="table"></table>
</div> hidden, onclick hide #data and show #table
</div>
loaddata.php
$tab_id = $_POST['tab_id'];
$tab_name = $_POST['tab_name'];
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
if (!$selectTabbladen->execute()) return false;
if ($selectTabbladen->rowCount() > 0) {
$tabblad_data = array();
while ($tabdata = $selectTabbladen->fetch()) {
$tabblad_data[] = array(
"id" => $tabdata['id'],
"document_soort" => $tabdata['document_soort'],
"voornaam" => $tabdata['voornaam'],
"relatie_naam" => $tabdata['relatie_naam'],
"tabblad" => $tabdata['document_status'],
"status" => $tabdata['document_status'],
"aanmaak_datum" => $tabdata['document_datum'] = date('d M Y H:i:s'),
"laatst_gewijzigd" => $tabdata['document_datumgewijzigd'] = date('d M Y H:i:s'),
);
}
print '</tbody>
</table>
';
$json_data = json_encode($tabblad_data);
print_r ($json_data);
}
ajax
$('body').on('click', '.tab_data', function () {
content.hide();
$('#dataa').show();
var tab_id = $(this).attr("id");
$.ajax({
type: "POST",
url: "loaddata.php",
data: {
tab_id: tab_id
},
dataType:"json",
success : function(data) {
$('#report-table').bootstrapTable({
data: data
});
}
});
});
As result I'm getting:
No matching records found
Can you help me please. What am I doing wrong?
If you have passed your tab_id correctly then the problem is with your query
Instead of
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
try this
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = ".$tab_id." ORDER BY document_datum");
Updated
Try this
$('#report-table').bootstrapTable({
'load': data
});

PHP + jQuery - Long Polling with database data aren't working (it doesn't break the loop)

I'm trying to implement a long polling system on my intranetwork, most of the users use IE and some use mobile too, that's why I'm trying to do it with long polling and not with websockets.
I followed this video http://www.screenr.com/SNH and I edited some code to work with my database. (Firebird)
It all seems ok, but it just doesn't break the loop. Maybe it's a kid mistake but I cannot see it, that is why I need your help!
Here's the code:
jQuery + Ajax:
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data){
alert('It Works');
var json = eval('(' + data + ')');
timestamp = json['timestamp'];
setTimeout('waitForMsg()',15000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("A - " + XMLHttpRequest + " - error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
</script>
getData.php ('DATAHORA' is timestamp field)
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
When I insert, update, or delete some data, the timestamp field are updated with the current timestamp.
I can see that the page enters the loop, but I don't know why it never ends.
Am I doing something wrong?
Thank you
I finaly found the solution.
And it was so simple. My code was not closing the connection with ibase_close
What i did was change it to close when finish the query process.
Then inside the loop, i need to reconnect the server again.
OMG how could i forgot that.
Thanks everyone.
Try replacing $currentmodif = $dados['DATAHORA']); with $currentmodif = $dados['HORA']); inside the while loop.
You're asking for an array key that doesn't exist, which will always be null, so your loop will run forever if $lastmodif is not null.
Change $currentmodif = $dados['DATAHORA']);, look:
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATA, HORA FROM AGENDAMENTOSBBM ORDER BY DATA DESC,HORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATA'].$dados['HORA']; // Before : $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
I don't know how look of your database design so, i suggest to you to change by yourself
Maybe your mistakes are on that lines. But i can't decide, because i have no time to fix it, i must do my project.
If i'm wrong, I'm sorry. Good luck
After rewriting the code in MySQL and scratching my head over why it seemed to be working just fine, I found the problem:
You need to set your initial var timestamp to 0, not null. If you set it to null, jQuery will send it as the string "null" (?timestamp=null). In PHP, it will compare this string "null" to whatever number $currentmodif is, so in the end you will never get into your while loop.
Try to eval your queries and see what they return, so you can validate the returned data and ensure the array $dados has the needed data and the keys to access any data of the array $dados.
var longpollError = false;
function longPoll(){
$.ajax({
url: "socialPolling",
type: 'GET',
dataType: 'json',
data: {param1: 'value1'},
timeout: 30000 // timeout every 10 sec
}).done(function(dataJson) {
//Success code goes here
})
.fail(function(data) {
longpollError = true; //mark this to true if there is an error
}).always(function(data) {
if(longpollError==false){ //if there is no error request it again
setTimeout(function() {
longPoll();
}, 3000);
}
})
}

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.

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