Keep Ajax alive - php

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.

Related

Ajax requests but doesn't get an answer form PHP script

I am working with a jQuery-function to trigger an ajax request on click. However, I don't get a result though the script should send a value via post-method. It looks like the PHP-script doesn't receive the value, but probably the problem is elsewhere.
Maybe somebody can tell me where the problem is.
doClick = function (sender){
var jid = sender.id;
if ($(window).width() < 768) {
$('.jwin').addClass('order-md-1').removeClass('order-md-2').removeClass('d-none');
$('.jobs').addClass('order-md-2').removeClass('order-md-1').removeClass('d-block').addClass('d-none');
var ink = document.getElementById('ajax').value;
$.ajax({
url:"get_job.php",
method:"POST",
data:{jid:jid},
cache:false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success:function(data)
{
//console.log(data.success);
if(data.success == TRUE)
{
//$('#ajax').text(data.nurl);
$('#title').text(data.title);
$('#crp').text(data.compnme);
$('#descript').html(data.jtxt);
$('#jadoci').text(data.city);
$('#jadost').text(data.state);
$('#connx1').css("display", "inline");
$('#connx2').css("display", "inline");
$('#applylink').css("display","block");
$('#applylink').attr('href',"links?jid="+jid);
if(data.url==''){
$('#applylink').css("display","none");
}
}else{
// Fade in
alert(data.success);
}
}
});
$('#returnmobile').append("<a href=''>"+jid+"</a>");
}
else {
$.ajax({
url:"get_job.php",
method:"POST",
data:{jid:jid},
cache:false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success:function(data)
{
//console.log(data.success);
if(data.success == TRUE)
{
//$('#ajax').text(data.nurl);
$('#title').text(data.title);
$('#descript').html(data.jtxt);
if(data.company==0){
$('#crp').text("Agent");
}
else{
$('#crp').text(data.compnme);
$('#crp').attr('href','company?id='+data.company)
}
$('#jadoci').text(data.city);
$('#jadost').text(data.state);
$('#connx1').css("display", "inline");
$('#connx2').css("display", "inline");
$('#applylink').css("display","block");
$('#applylink').attr('href',"links?jid="+jid);
if(data.url==''){
$('#applylink').css("display","none");
}
}else{
// Fade in
alert(data.success);
}
}
});
//alert('More than 960');
}
};
And the PHP-code:
require "config.php";
$jid = $_POST["jid"];
$ipa = $_SERVER['REMOTE_ADDR'];
$query = $con->query("SELECT jla.title AS title, jla.summary AS jtxt, jla.city AS city, jla.state AS state, jla.company AS corp, c.name AS company, jla.url AS url, jla.id AS coid FROM jobs jla LEFT JOIN companies c ON c.id = jla.company WHERE jla.id = $jid");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$output = array('success'=>TRUE,
'nurl'=>("<b>Does</b> it work? Yes!"),
'company'=>$row['corp'],
'compnme'=>$row['company'],
'title'=>$row['title'],
'city'=>$row['city'],
'state'=>$row['state'],
'coid'=>$row['coid'],
'url'=>$row['url'],
'jtxt'=>$row['jtxt']);
$quip0 = $con->query("SELECT * FROM clicks WHERE ip = '$ipa' AND job_id = '$jid'");
if($quip0->num_rows < 1){
$quip1 = "INSERT INTO clicks (ip, job_id) VALUES ('$ipa','$jid')";
if ( $con->query($quip1) === TRUE) {
echo json_encode($output,JSON_FORCE_OBJECT);
}
}
else {
echo json_encode($output,JSON_FORCE_OBJECT);
}
}
}
Again: the result I receive seems to be empty. Even in the inspect-mode in Chrome I don't see values that I'd expect, making me suspicious that the $jid value wouldn't be delivered correctly. Btw: sender.id works so far. I used to test this.
You aren't sending json or expecting json at server so remove:
contentType: "application/json; charset=utf-8",
There might be several issues. One common problem is when the request is done from a different domain the server does not serve the request. Use header('Access-control-allow-origin: *') at the start of the file or the function
Use CORS carefully

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.

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

Javascript won't post variable

Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.

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