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?
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).
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
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
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();