In this scenario, a feedback database is queried using AJAX every 10 seconds to display fresh feedback in a div. However, the code encounters an issue where it only displays two feedback items instead of continuously updating with new ones.
The error originates from the lack of a mechanism to trigger subsequent AJAX calls after the initial one. To rectify this, introduce a setInterval() or setTimeout() function to automate the call repetition.
setInterval() Approach:
<code class="javascript">setInterval(get_fb, 10000);</code>
In this variation, get_fb() executes every 10 seconds regardless of the status of the previous AJAX call.
setTimeout() with Success Callback:
<code class="javascript">var feedback = $.ajax({ type: "POST", url: "feedback.php", async: false }).success(function() { setTimeout(function() { get_fb(); }, 10000); }).responseText;</code>
With this method, the next call executes once the current AJAX call completes successfully.
setTimeout() with Complete Callback:
<code class="javascript">var feedback = $.ajax({ type: "POST", url: "feedback.php", async: false }).complete(function() { setTimeout(function() { get_fb(); }, 10000); }).responseText;</code>
This approach ensures that a new AJAX call is triggered regardless of the outcome of the previous one.
The example provided on jsfiddle demonstrates the correct implementation of both methods. Note that the success callback works only once due to an error returned by the AJAX call.
The above is the detailed content of Why are Only Two Feedback Items Displayed When Using jQuery AJAX Calls on a 10-Second Interval?. For more information, please follow other related articles on the PHP Chinese website!