Home >Backend Development >PHP Tutorial >How to Update a Feedback Display with AJAX Every 10 Seconds in jQuery?

How to Update a Feedback Display with AJAX Every 10 Seconds in jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 01:54:021078browse

How to Update a Feedback Display with AJAX Every 10 Seconds in jQuery?

jQuery: Updating Feedback Display via AJAX Every 10 Seconds

A scenario arises where you want to update a feedback div every 10 seconds using AJAX. To achieve this, you may use the following jQuery and PHP codes.

jQuery Script:

<code class="javascript">$(document).ready(function(){
  setInterval(get_fb, 10000);
});

function get_fb(){
  var feedback = $.ajax({
    type: "POST",
    url: "feedback.php",
    async: false
  }).responseText;

  $('div.feedback-box').html(feedback);
}</code>

PHP Script:

<code class="php">$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
  $name = $row['name'];
  $location = $row['location'];
  $feedback = $row['feedback'];

  echo "
    <p>Name: $name, Location: $location, Feedback: $feedback.</p>
    ";
} </code>

Explanation:

This code employs the setInterval() function to call the get_fb() function every 10 seconds. The get_fb() function uses an AJAX request to retrieve feedback data from a database and updates the content of the div with the retrieved feedback.

Alternative Option:

If you want to run the get_fb() function only after the AJAX call is successful, you can use the .ajax().success() callback:

<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>

The above is the detailed content of How to Update a Feedback Display with AJAX Every 10 Seconds in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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