How to Continuously Fetch Data with jQuery Ajax Every 10 Seconds?

Patricia Arquette
Release: 2024-11-04 03:53:29
Original
848 people have browsed it

How to Continuously Fetch Data with jQuery Ajax Every 10 Seconds?

jQuery: Calling 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.

setInterval()

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>
Copy after login

This code will call the get_fb() function every 10 seconds.

Ajax Call Completion Callback

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>
Copy after login

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>
Copy after login

Both of these methods will initiate the next Ajax call once the current one has completed.

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!