I have a very annoying bug. My AJAX queries are failing anywhere up to 20-30 times with 500 GET and POST server errors, but then all of a sudden they work.
It seems to be completely random, as sometimes I will load the page and it will work fine for a full day of usage, but then the next day it will fail and I have to catch and retry it up to 30 times to get it to work.
AJAX
function getData(){
//Get Data and build contributions Table
$.ajax({
url: 'assets/processes/dash/support/get-data.php', // URL of php command
tryCount : 0,
retryLimit : 3,
type: 'POST', //TYPE
data: {'id': id}, //Variables in JSON FORMAT
success: function(results) { //SUCCESSFUL REQUEST FUNCTION
var result = $.parseJSON(results);
console.log(result);
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
$.ajax(this);
return;
} else {
//handle error
}
}
}); // end ajax call
PHP
<?php
include "../../../includes/database.php";
$totalOpen = $db->pdo_query_assoc("xdGetTotalUnresolvedTickets
1,0,0,0,0,0");
$totalWaitState = $db->pdo_query_assoc("xdGetWaitState 1,0,0,0,0,0");
$nonWaitState = $totalOpen['xdGetTotalUnresolvedTickets'] -
$totalWaitState['xsGetWaitState'];
$getStaff = $db->query("SELECT * FROM user WHERE role = 'Technical
Support'");
$getStaffArray = array();
foreach($getStaff as $key => $value){
$sqlUsername = $value['sqlName'];
$pdo_today = $db->pdo_query_assoc("xsGetTotalResolvedTicketsToday
'$sqlUsername'");
$start = date('Y-m-d ', strtotime('-7 days'));
$end = date('Y-m-d ', strtotime('+1 days'));
$pdo_last_week = $db->pdo_query_assoc("xsGetTotalResolvedTicketsToday
'$sqlUsername','$start','$end'");
$getCompletionRate = $db->pdo_query_assoc('xStaffTicketCompletionRate
"'.$sqlUsername.'"');
$getWeeklyRate = $db->pdo_query_assoc('xLastSevenPreviousSeven
"'.$sqlUsername.'"');
$getStaffArray[$key]['staffName'] = $value['user'];
$getStaffArray[$key]['staffFullName'] = $value['name'];
$getStaffArray[$key]['colourScheme'] = $value['colourScheme'];
$getStaffArray[$key]['today'] =
$pdo_today['xsGetTotalResolvedTicketsToday'];
$getStaffArray[$key]['thisWeek'] =
$pdo_last_week['xsGetTotalResolvedTicketsToday'];
$getStaffArray[$key]['completionRate'] = $getCompletionRate['Level'];
$getStaffArray[$key]['thisTimeLastWeek'] =
round($getWeeklyRate['Percentage'],1);
$getStaffArray[$key]['weeklyRateLevel'] = $getWeeklyRate['Level'];
$getStaffArray[$key]['weeklyPrevious7'] = $getWeeklyRate['Previous 7
Days'];
$getStaffArray[$key]['weeklyEarlier7'] = $getWeeklyRate['Earlier 7
Days'];
}
$tickets = array('totalCurrent' => $totalOpen, 'totalWaitState' =>
$totalWaitState, 'totalNoneWaitState' => $nonWaitState);
$allData = array('totalTickets' => $tickets, 'staff' => $getStaffArray);
echo json_encode($allData, JSON_FORCE_OBJECT);
?>
I know at the moment the trycount doesnt work properly, as instead of trying 3 times it tries unlimited amount until it works. Any one have any ideas as to why this could be happening?
They always fail on the php file, like the query cant be executed.
ERROR
GET http://mysite/get-events.php 500 (Internal Server Error)
jquery.min.js:4
Related
I want to achieve a pseudo real time chat app inside a Codeigniter framework using long polling. I know it's not the best option (I could try with HTML5 Websocket), but I'm on a cPanel shared account so I don't have any privileges on installing anything
So, let's get back to the issue itself.
Basically, I use a .js file similar to the one below:
//get server time
var time;
$.ajax( {
url: JS_BASE_URL + 'admin/users/get_time',
success: function( dataResponse ) {
time = dataResponse;
},
type: 'GET'
} );
//long polling AJAX
function getNewMsgs() {
$.ajax( {
url: JS_BASE_URL + 'admin/users/get_new_msgs',
type: 'POST',
// send the time
data: { time: time, sender_id: sender_id },
dataType: 'json',
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
success: function( dataResponse ) {
// update the time
time = dataResponse.time;
// show the new messages
dataResponse.msgs.forEach( function( msg ) {
preparePost('in', (msg.date_sent), msg.sender_id, 'avatar3', msg.message);
} );
// repeat
setTimeout( getNewMsgs(), 1000 );
},
error: function (XMLHttpRequest, textStatus, errorThrown){
setTimeout( getNewMsgs(), 1000 );
}
} );
}
getNewMsgs(); // this one is on the document ready
The php get_new_msgs function in Users controller:
function get_new_msgs() {
echo json_encode( array(
'msgs' => $this->aauth->start_polling($this->aauth->get_user()->id),
// response again the server time to update the "js time variable"
'time' => time()
) );
die();
}
And the model function start_polling:
function start_polling($receiver_id) {
// get the time
$time = $this->CI->input->post( 'time' );
$sender_id = $this->CI->input->post( 'sender_id' );
// some crappy validation
if( !is_numeric( $time ) ) {
return array();
}
$time = date('Y-m-d G:i:s',$time);
// -> 2010-10-01
//$time = $time['year'] + '-' + $time['mon'] + '-' + $time['mday'];
while( true ) {
$where = 'date_sent >= "' . $time . '" AND ((receiver_id=' . $receiver_id . ' AND pm_deleted_receiver IS NULL AND sender_id=' . $sender_id . ' AND pm_deleted_sender IS NULL) OR (receiver_id=' . $sender_id . ' AND pm_deleted_receiver IS NULL AND sender_id=' . $receiver_id . ' AND pm_deleted_sender IS NULL))';
$query = $this->aauth_db->where($where);
$query = $this->aauth_db->order_by('id','ASC');
$query = $this->aauth_db->get( $this->config_vars['pms']);
//die($this->aauth_db->last_query());
if( $query->num_rows() > 0 ) {
$result = $query->result();
if ($this->config_vars['pm_encryption']){
$this->CI->load->library('encrypt');
foreach ($result as $k => $r)
{
$result[$k]->title = $this->CI->encrypt->decode($r->title);
$result[$k]->message = $this->CI->encrypt->decode($r->message);
}
}
echo json_encode($result);
die();
} else {
sleep( 1 );
continue;
}
}
}
Now, the issue is that whenever I run the page with the chat, a request is loaded and waiting for a response from the server. But, no other requests will finish.. it seems that the other requests sent after the long polling are waiting for that first one to finish.. Even if I stop the script, the page will load very slow..
Any idea on what I'm missing?
Thank you in advance!
I am trying to make a facebook webpage messenger like app and I use AJAX in client side and php on my server side.
My AJAX code:
function longPoll(timestamp)
{
var queryString = {'timestamp' : timestamp};
var shouldDelay = false;
$.ajax(
{
type: 'GET',
async: true,
url: 'pollMsg.php',
data: queryString,
timeout: 5000,
cache: false
}
).done(function(data){
var array = jQuery.parseJSON(data);
for (var i = 0; i < array.length; i++) {
$('#msgTable > tbody:last-child').append('<tr><td><b>' + array[i].sender + '</b><br/>' + array[i].timestamp + '</td><td><b>' + array[i].title + '</b><br/>' + array[i].content + '</td></tr>');
}
longPoll(obj.timestamp);
}).fail(function(jqXHR, textStatus, errorThrown) {
//shouldDelay = textStatus !== "timeout";
}).always(function() {
var delay = shouldDelay ? 5000: 0;
if (shouldDelay) {
shouldDelay = false;
window.setTimeout(longPoll, delay);
}
});
}
// initialize jQuery
$(function() {
longPoll();
});
My PHP code:
//set php runtime to unlimited
set_time_limit(10);
while (true) {
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : '1970-01-01 00:00:00';
$sql = "select * from post where (receiver = ? or sender = ?) and postat > str_to_date(?, '%Y/%m/%d %H:%i:%s')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $username, $last_ajax_call);
$result = $stmt->execute();
$rows = $stmt->get_result()->fetch_all();
if (count($rows) > 0) {
$result = array();
foreach ($rows as $row) {
$data = array (
'sender' => $row[3],
'timestamp' => $row[5],
'title' => $row[1],
'content' => $row[2]
);
array_push($result, $data);
}
$json = json_encode($result);
echo $json;
break;
} else {
sleep( 1 );
continue;
}
}
I found that if I once click on the page with the AJAX code, when I change to other page in the same webserver, I will get a nginx error (as I use nginx).
What is the problem in my code? I have found some example of long polling and it gives me similar code. Thank you.
When I restart php-fpm, everything is okay, which means that I have generated so many request so that the server cannot handle.
OK I'm trying to pull events from a MySQL database to populate a calendar. The start times are stored in Unix time so I have used the following events source.
events: {
url: '/php/booking_events.php',
type: 'POST',
data: {
start: start.unix(),
end: end.unix(),
branch: branch.id_office,
instrument: inst
},
error: function() {
alert('there was an error while fetching events!');
},
}
This brings up the first problem, when I run this I get an error in dev tools saying start is not defined? Doesn't the calendar automatically generate the start and end times?
Secondly, if I manually enter parameters into my PHP it generates a JSON array then echoes it back but the script is constantly saying 'there was an error while fetching events!'
<?php
require_once('../Connections/localhost.php');
require_once("../Includes/functions.php");
//if (!isset($_POST['start']) || !isset($_POST['end'])) {
// die("Please provide a date range.");
//}
//$range_start = parseDateTime($_POST['start']);
//$range_end = parseDateTime($_POST['end']);
//$branch = GetSQLValueString($_POST['id_office'], "int");
//$inst = GetSQLValueString($_POST['instrument'], "int");
$range_start = '1433462401';
$range_end = '1433721599';
$branch = 2;
$inst = 3;
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_POST['timezone'])) {
$timezone = new DateTimeZone($_POST['timezone']);
}
// Query database to get events
mysql_select_db($database_localhost, $localhost);
$query_Events = sprintf("SELECT hm_classes.datetime, hm_classes.id_student, hm_classes.inst FROM hm_classes INNER join hm_rooms ON hm_classes.id_room = hm_rooms.id_room WHERE datetime BETWEEN %s AND %s AND id_office = %s AND inst = %s", $range_start, $range_end, $branch, $inst);
$Events = mysql_query($query_Events, $localhost) or die(mysql_error());
while ($row = mysql_fetch_assoc($Events)){
$id = $row['id_class'];
$title = 'Booking';
$start = date('c', $row['datetime']);
$end = date('c', ($row['datetime'] + hoursToSecods($row['Session'])));
$input_arrays[]= array(id => $id, title => $title, start => $start, end => $end, allDay =>'false');
}
// Send JSON to the client.
echo json_encode($input_arrays);
?>
The echoed result of this is
[{"id":"1","title":"Booking","start":"2015-06-05T14:00:00+02:00","end":"2015-06-05T15:00:00+02:00","allDay":"false"}]
which is what I think fullcalendar is after? Any help would be greatly appreciated.
OK I think I have solved this problem, following kamlesh.bar's suggestion I went to look at http://www.jqueryajaxphp.com/fullcalendar-crud-with-jquery-and-php/.
After looking through his code I separated my AJAX request out from the main fullcalendar script and gave it it's own function.
function getEvents(){
$.ajax({
url: 'booking_events.php',
type: 'POST', // Send post data
data: {type: 'fetch',
branch: $('#branch').val(),
inst: $('#instrument').val()},
async: false,
success: function(s){
json_events = s;
}
})
}
Then in fullcalendar I set the events as
events: JSON.parse(json_events),
This is now allowing the results generated by the php to be entered into the calendar.
As for that start: stat.unix() issue, I am just using strtotime in php to change that to a Unix timeformat
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);
}
})
}
I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.