I have a mysql feedback database constructed like this:
name | location | feedback
Ryan | England | great support
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
So I have constructed this:
$(document).ready(function(){ new get_fb(); }); function get_fb(){ var feedback = $.ajax({//Ajax type: "POST", url: "feedback.php", async: false }).responseText;//end of ajax $('div.feedback-box').html(feedback).delay(10000).queue(function() { new get_fb(); }); }
And here's my PHP file:
$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> "; }
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
What am I doing wrong? Thanks :)
The jQuery code to call AJAX in every 5 seconds Here is the jQuery code: $(document). ready(function(){ sendRequest(); function sendRequest(){ $. ajax({ url: "example.
Use just setTimeout(executeQuery, 5000); instead of setTimeout('executeQuery()', 5000); - it's shorter and faster.
Use setInterval() when you want to send AJAX request at a particular interval every time and don't want to depend on the previous request is completed or not. But if you want to execute the AJAX when the previous one is completed then use the setTimeout() function.
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.
Are you going to want to do a setInterval()
?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success()
callback:
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); }
Or use .ajax().complete()
if you want it to run regardless of result:
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); }
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With