Home >Backend Development >PHP Tutorial >How to Continuously Fetch Data with jQuery Ajax Every 10 Seconds?
In the given scenario, the goal is to display new feedback items in a div every 10 seconds using Ajax. However, the code provided only shows two items and then stops.
The issue is that the code is missing a mechanism to periodically initiate the Ajax call. To accomplish this, consider using the setInterval() function.
The setInterval() function takes a callback function and an interval in milliseconds as its arguments. It executes the callback function after the specified interval elapses and continues to do so until it is cleared.
For example, you could use setInterval() as follows:
<code class="javascript">setInterval(function(){get_fb();}, 10000);</code>
This code will call the get_fb() function every 10 seconds.
Alternatively, you could have the Ajax call initiate the next one upon its completion. This can be achieved using the success() or complete() methods of the Ajax call.
Using success():
<code class="javascript">function get_fb(){ var feedback = $.ajax({ type: "POST", url: "feedback.php", async: false }).success(function(){ setTimeout(function(){get_fb();}, 10000); }).responseText; $('div.feedback-box').html(feedback); }</code>
Using complete():
<code class="javascript">function get_fb(){ var feedback = $.ajax({ type: "POST", url: "feedback.php", async: false }).complete(function(){ setTimeout(function(){get_fb();}, 10000); }).responseText; $('div.feedback-box').html(feedback); }</code>
Both of these methods will initiate the next Ajax call once the current one has completed.
The use of setInterval() or Ajax call completion callbacks allows for continuous retrieval and display of new feedback items at regular intervals, addressing the issue of only showing two items before stopping.
The above is the detailed content of How to Continuously Fetch Data with jQuery Ajax Every 10 Seconds?. For more information, please follow other related articles on the PHP Chinese website!