I am using a remote API to pull an application's console logs every 2 seconds using AJAX. This works fine in all cases with the exception of the user clicking a link on the page to move elsewhere. Doing so triggers the Error callback without actually providing any data, although refreshing the page does not.
Can anyone perhaps tell me what could be causing this and a potential solution to the problem?
<script>
var server_id = getUrlParameter('id');
var lastFetchTime = 1;
$(document).ready(function()
{
getConsoleMessages();
setInterval(function()
{
getConsoleMessages();
},2000);
});
function getConsoleMessages()
{
var consoleBox = document.getElementById("console");
$.ajax({
type: "POST",
url: "consoleHandler.php",
data: { 'action': 'getConsoleMessages', 'server_id': server_id, 'since': lastFetchTime },
dataType: 'json',
success: function(data)
{
console.log(data);
var messages = data['message']['chatdata'];
if (messages.length > 0)
{
messages.forEach( function (item)
{
// Skip lines we've already displayed
if (lastFetchTime >= item.timestamp)
{
return;
}
var timestamp = item.time; // /Date(1440823073243)/
var timestamp = timestamp.substring(timestamp.lastIndexOf("(")+1, timestamp.lastIndexOf(")"));
var contents = item.message;
lastFetchTime = item.timestamp;
// Get Date/Time in Milliseconds
var date = new Date(parseInt(timestamp));
var time = pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
console_log("<font color='blue'>[" + time + "]</font>" + " " + contents);
});
}
consoleBox.scrollTop = consoleBox.scrollHeight;
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
}
});
};
</script>
consoleHandler.php
$action = $_POST['action'];
$response = array();
switch ($action)
{
case "getConsoleMessages":
{
foreach ($_SESSION['servers'] as $server)
{
if ($server['whmcs_id'] == $_POST['server_id'])
{
$mcmyadmin = new McMyAdmin($server['mcma_user'], $server['mcma_pass'], $server['mcma_ip'], $server['mcma_port']);
$result = $mcmyadmin->getChat($_POST['since']);
$response['status'] = "success";
$response['message'] = $result;
}
}
echo json_encode($response);
break;
}
}