Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

php - jQuery - Call ajax every 10 seconds

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

question from:https://stackoverflow.com/questions/5687600/jquery-call-ajax-every-10-seconds

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...