Basic Ajax Cache Issue - php

I have a single page that I need to on occasion asynchronously check the server to see if the status of the page is current (basically, Live or Offline). You will see I have a function with a var live that is set when the page initially loads. I then do an ajax request to the server to retrieve whether the status of live is true or false. I compare the initial live variable with the newly returned data json object. If they're the same I do nothing, but if there different I apply some css classes. I recursively run it with setTimeout (Is there a better way to recursively do this?).
My Problem:
data.live doesn't change from it's initial time it runs even when it has changed in the db. I know my mysql is working because it returs the right value on the initial load. It seems like a caching issue.
Any help is greatly appreciated.
function checkLive() {
var live = <?=$result["live"]?>;
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
success: function(data) {
console.log('checking for updates... current:' + data.live);
if (data.live == live) {
return;
} else {
var elems = $('div.player_meta, object, h3.offline_message');
if (data.live == '1') {
elems.removeClass('offline').addClass('live');
} else {
elems.addClass('live').addClass('offline');
}
}
}
});
setTimeout(function() { checkLive() } ,15000);
}
checkLive();

Use the cache option of $.ajax() to append a cache breaker to the URL, like this:
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
cache: false,
//success, etc.
});
If that doesn't resolve it...look at firebug, see if a request is being made (it should be after this for sure), if it's still getting an old value, the issue is in PHP, not JavaScript.
Unrelated to the issue, just a side tip: If you need no parameters, you can skip the anonymous function call, this:
setTimeout(function() { checkLive() } ,15000);
can just be:
setTimeout(checkLive, 15000);

You can check if it's a caching issue by adding unique ID to the url:
change url: '/live/live.php', to url: '/live/live.php?'+new Date().getTime(),
Cheers
G.

I think Nick Craver has the right response.
For the other point of the question which is you SetTimeout , you could use SetInterval() and avoid the recursive call. But in fact I would stay with a setTimeout() and add a factor on the 15000 time. set that factor as a parameter of checklive. Then you will have a check which will be delayed progressively in time. This will avoid a LOT of HTTp requests from the guy which his still on your page since 48 hours.
Chances are that most of the time users will check for new pages in a regular manner, but someone staying for a very long time on a page is maybe not really there. Here's a piece of code I had doing that stuff.
function checkLive(settings) {
(...) //HERE ajax STUFF
setTimeout(function() {
if ( (settings.reload <2000000000) && (settings.growingfactor > 1) ) {
checkLive(settings);
settings = jQuery.extend(settings,{reload:parseInt(settings.reload*settings.growingfactor,10)});
}
},settings.reload);
}

Related

PHP script not echoing data when called via AJAX

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

PHP jQuery Long Polling Chat Application

I've made a simple PHP jQuery Chat Application with Short Polling (AJAX Refresh). Like, every 2 - 3 seconds it asks for new messages. But, I read that Long Polling is a better approach for Chat applications. So, I went through some Long Polling scripts.
I made like this:
Javascript:
$("#submit").click(function(){
$.ajax({
url: 'chat-handler.php',
dataType: 'json',
data: {action : 'read', message : 'message'}
});
});
var getNewMessage = function() {
$.ajax({
url: 'chat-handler.php',
dataType: 'json',
data: {action : 'read', message : 'message'},
function(data){
alert(data);
}
});
getNewMessage();
}
$(document).ready(getNewMessage);
PHP
<?php
$time = time();
while ((time() - $time) < 25) {
$data = $db->getNewMessage ();
if (!empty ($data)) {
echo json_encode ($data);
break;
}
usleep(1000000); // 1 Second
}
?>
The problem is, once getNewMessage() starts, it executes unless it gets some response (from chat-handler.php). It executes recursively. But if someone wants to send a message in between, then actually that function ($("#submit").click()) never executes as getNewMessage() is still executing. So is there any workaround?
I strongly recommend that you read up on two things: the idea behind long polling, and jQuery callbacks. I'll quickly go into both, but only in as much detail as this box allows me to.
Long polling
The idea behind long polling is to have the webserver artificially "slow down" when returning the request so that it waits until an event has come up, and then immediately gives the information, and closes the connection. This means that your server will be sitting idle for a while (well, not idle, but you know what I mean), until it finally gets the info that a message went through, sends that back to the client, and proceeds to the next one.
On the JS client side, the effect is that the Ajax callback (this is the important bit) is delayed.
jQuery .ajax()
$.ajax() returns immediately. This is not good. You have two choices to remedy this:
bind your recursion call in the success and error callback functions (this is important. the error function might very well come up due to a timeout)
(see below):
Use This:
var x = $.ajax({blah});
$.when(x).done(function(a) { recursiveCallHere(); });
Both amount to the same thing in the end. You're triggering your recursion on callback and not on initiation.
P.S: what's wrong with sleep(1)?
In long polling new request should be initiated when you have received the data from the previous one. Otherwise you will have infinite recursion in browser freezing.
var getNewMessage = function() {
$.ajax({
url: 'chat-handler.php',
dataType: 'json',
data: {action : 'read', message : 'message'},
success: function(data) {
alert(data);
getNewMessage(); // <-- should be here
}
});
}

jQuery update div the moment a table is updated

I'm trying to figure out a way to have jQuery update a div the moment a table in mysql is updated. I've spent a vigorous amount of hours searching online for an answer, and so far, nothing. Can anyone help me out with this problem?
Well the steps you should probably take are:
Have a piece of AJAX code that queries the server for a change (like row count changing or something along those lines). Using jQuery you can do that:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'hasDataChanged.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// return a JSON string like { "hasChanged" : "true" } or something
if (data.hasChanged) {
// data has changed, do something
}
}
});
}
Then you can use the Javascript method setInterval to call the code every few seconds. It is unrealistic to do it instantly.
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
You'll have to poll the database via ajax and php every (couple of) second(s) and check if the data has changed. if so, update the div.
i don't think there's a way of detecting the exact moment the db is updated.
Useful links on polling. It attempts to make server send data to browser:
http://onepixelahead.com/2010/04/30/html5-web-sockets-example/
http://en.wikipedia.org/wiki/Comet_(programming))

Truly Random String in Javascript Asynchronously

I am using a javascript function to generate a random string:
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
/*$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
return html;
}
});*/
return (S4()+S4()+S4()+S4());
}
And I want to make it utilize a php uuid library that I've found, the problem is I need it to run in javascript. I use the guid() function a lot and I've been trying to think of an elegant way of grabbing the uuid, that I request using the ajax object (commented out above). The uuid page that just prints random uuids each time is sitting locally next to this page. I would not like to make the request synchronous because, like I said, I use it quite a bit and would prefer to not have everything halt every time this thing makes a request. Or perhaps there's a method I could use of jQuery that be as fast and not hinder performance?
I'm not adverse to changing things up a bit, like would the best practice here to acquire a uuid on load? But the number of UUIDs I generate is completely dynamic, and dependent upon the user.
Thank you!
Check the uniqid() function from phpjs.org.
How about adding a callback argument to the guid() function, wherein you can assign a value to something:
function guid(callback) {
$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
callback(html);
}
});
}
var value;
guid(function (result) {
value = result;
});

AJAX Post Not Sending Data?

I can't for the life of me figure out why this is happening.
This is kind of a repost, so forgive me, but I have new data.
I am running a javascript log out function called logOut() that has make a jQuery ajax call to a php script...
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
}
});
}
the php function it calls is here:
if(isset($_POST['log_out'])){
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('logOutSuccess')";
$connection->runQuery($query); // <-- my own database class...
// omitted code that clears session etc...
die();
}
Now, 18 hours out of the day this works, but for some reason, every once in a while, the POST data will not trigger my query. (this will last about an hour or so).
I figured out the post data is not being set by adding this at the end of my script...
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('POST FAIL')";
$connection->runQuery($query);
So, now I know for certain my log out function is being skipped because in my database is the following data:
alt text http://img535.imageshack.us/img535/2025/screenshot20100519at125h.png
if it were NOT being skipped, my data would show up like this:
alt text http://img25.imageshack.us/img25/8104/screenshot20100519at125.png
I know it is being skipped for two reasons, one the die() at the end of my first function, and two, if it were a success a "logOutSuccess" would be registered in the table.
Any thoughts? One friend says it's a janky hosting company (hostgator.com). I personally like them because they are cheap and I'm a fan of cpanel. But, if that's the case???
Thanks in advance.
-J
Ok, for those interested.
I removed the full URL http://www.mydomain.com/functions.php
and replaced it with the local path functions.php and that did the trick.
Apparently AJAX has issues with cross domain ajax calls and I'm not on a dedicated server, so I imagine what's happening is every couple hours (or minutes) I am somehow hitting my script from a different location causing AJAX to dismiss the POST data.
-J
Try enabling error reporting on the jquery $.ajax function, your code would look something like
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus+" - "+errorThrown);
}
});
}
See if that sheds light on your situation.
I have a strong feeling that it's more of a server side issue rather than the client's.
The odd thing is that you see the problem for a period of time. If the client works at all, then at the minimum refreshing the page or restarting the browser should fix it.
The die() at the end of the function is suspicious, but I am not quite sure how it will affect it.
Btw you can see http headers in FireBug's Net tab, to know whether those parameters has been sent properly.

Categories