Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery/Ajax call with timer

I have a php page that echos out rows from a database. I want to call it via jquery/ajax every 30 seconds. But I also want to be able to call the page at any time so that if I add a record via the form, once the form submits I want the page via called to ajax to update the results right away. Can anyone point me in the right direction or provide some base code so I can try to figure this out? Still very new to jquery/ajax.

like image 556
John Avatar asked Dec 28 '10 00:12

John


People also ask

How to set timeout in jQuery AJAX?

In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function. This function executes the given Ajax code after some amount of given time.

How do you call AJAX every 5 seconds?

Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.

What is the default timeout for jQuery AJAX?

The default value is 0. Which means there is no timeout. Return value – The ajax timeout option does not return any value.


1 Answers

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout ); setInterval ( expression, interval ); 

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {     //call $.ajax here }, 5000); //5 seconds 

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {     //call $.ajax here }, 30000); // 30 seconds 

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

like image 80
treeface Avatar answered Oct 05 '22 14:10

treeface