5

How can I use jQuery to constantly run a PHP script and get the response every second and also to send small bits of data on mouse down to the same script?

Do I really have to add some random extension just to get such a simple timer to work?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Getting the response ever second is a bit excessive... can you change this to 15 seconds at least ? – alex Mar 31 '09 at 05:18

5 Answers5

25

To iterate is human, to recurse divine.
-L. Peter Deutsch

var req = function () {
    $.ajax({
        url : 'http://example.com/yourscript.php',
        complete : function () {
            req();
        }
    });
};
req();

In case it's not obvious, the above will make a new request as soon as the previous one completes, forever. You could also set a 1 second delay between requests as follows:

var req = function () {
    $.ajax({
        url : 'http://example.com/yourscript.php',
        complete : function () {
            setTimeout(function () {
                req();
            }, 1000);
        }
    });
};
req();
Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
  • This will occur many times a second and bring the server down with its load – Ali Mar 31 '09 at 05:44
  • I presume you downvoted before I added the 2nd version. The basic idea is to use a callback rather than simply polling once per second. – Andrew Hedges Mar 31 '09 at 05:47
  • 2
    And, anyway, it won't make many requests per second. It will make 1 request at a time. 1 request, when it completes, make the next request. So, maybe you should undo your downvote? – Andrew Hedges Mar 31 '09 at 05:49
  • Andrew's right, that code not only works, it is exactly what Steve asked for. – mclaughj Mar 31 '09 at 06:28
  • This will generally work ok - though I think a more robust approach is to have the response tell the application how long it should wait before contacting the server again, as it's often in a position to calculate an optimal duration. – Bittercoder Mar 31 '09 at 06:30
  • Sure, this is a stripped down case. What it *should* do is inspect the response as you say and decide whether *and* when to make the next one. – Andrew Hedges Mar 31 '09 at 06:36
  • Elegant and perfect solution – Saad Suri Jul 05 '17 at 08:49
1
function doAjax(data){
    $.ajax({
    type: "POST",
    data: data,
    url: 'http://example.com/yourscript.php',
  });
}
// Set interval
setInterval('doAjax()',1000);
// Set event handler
$(document).mousedown(function(){
  doAjax({key: 'value'});
});

You could replace $(document) with an actual element if you don't want to capture clicks on the whole page.

You can do a lot more with the ajax function if you are looking for callbacks etc: http://docs.jquery.com/Ajax/jQuery.ajax

Graham
  • 353
  • 3
  • 8
1

//All pings you need:

ping.pushCallback(function() { YourCallback(); });
$.data(document.body, 'data_ping', ping);

//------------------------------------------------------ //Script

$.ping = function(url, options) {
    this.url = url;
    this.options = $.extend({
        delay: 2000,
        dataType: 'json',
        timeout: 10000,
        data: {},
        callbacks: []
    }, options);
    this.queue();
};
$.ping.prototype = {
    queue: function() { var self = this;
        setTimeout(function() {
            self.send();
        }, self.options.delay);
    },
    send: function() { var self = this;
        $.ajax(self.url, {
            success: function(data) {
                for (var i in self.options.callbacks) {
                    self.options.callbacks[i](data);
                }
            },
            complete: function() {
                self.queue();
            },
            dataType: self.options.dataType,
            data: self.options.data,
            type: "GET",
            cache: false,
            timeout: self.options.timeout
        });
    },
    setData: function(key, value) { 
        this.options.data[key] = value;
    },
    pushCallback: function(callback) {
        this.options.callbacks.push(callback);
    }
};
hrr
  • 11
  • 2
0

You don't have to add some random extension. There are native javascript functions setInterval and setTimeout for doing stuff on set intervals. You would probably want to do something like

function ajaxPing() {
  ...
}

setInterval("ajaxPing()", 1000);

$(element).mousedown(ajaxPing);

On the other hand, if you really want to do the pinging every second, it would probably be sufficient to just store your data in variables on mousedown and submit it on next ping (that will happen in less than a second).

kkyy
  • 12,214
  • 3
  • 32
  • 27
0

You can put the code for pinging the server in a function, then do something like this:

setInterval('ping()',1000); //this will ping 1000 milliseconds or 1 second
Ali
  • 261,656
  • 265
  • 575
  • 769