Pepe Perez
Pepe Perez

Reputation: 121

How to refresh mysql posts every 1 second

I use ajax to save user posts/comments into a mysql table without page refresh.

First: I have this <div id="posts-container"></div>

Second: I've tried using Jquery load() to loop in table and echo the posts, with the following code:

var auto_refresh = setInterval(function() {
                           $('.posts-container').load("refresh_p.php").fadeIn();
                       }, 0 );

But it doesn't work, page refreshes but content doesn't load, anybody knows why?

Third: If i copy the code that contains refresh_p.php and paste into the data gets loaded successfully. A little weird? Yes. Hope get any help :)

EDIT: I fixed it, the problem was in refresh_p.php it was expecting the parameter 'profile_id' i modified the function to this:

1: profile.php

search_user = document.getElementById('user_from').value; 
var auto_refresh = setInterval(function() {
                           $('.posts-container').load("refresh_p.php?search_user="+search_user).fadeIn();
                       }, 5000 );

2: refresh_p.php

$profile_id = $_GET['search_user'];

All good, but now the whole page refreshes every 5 seconds. I just want the div 'post-container' to refresh.

I've used this function before to refresh a chat box and it worked, only refreshes the div i wanted to. but here it refreshes the entire page.

Upvotes: 0

Views: 1107

Answers (3)

XCS
XCS

Reputation: 28137

Don't use setInterval. Do recursive calls on jQuery load complete, this way you make sure that calls are sent one AFTER another, not at the same time.

Try this:

var auto_refresh =  function () {
    $('.posts-container').load("refresh_p.php", function(){
            setTimeout(auto_refresh, 800);
        }).fadeIn();
}
auto_refresh();

Also, .fadeIn() only works the first time, after that you have to hide the div before showing it again.

Demo: http://jsfiddle.net/P4P9a/1/ (might be slow because it is loading an entire page).

LE: As I think you are not returning an HTML page you should use $.get instead of $.load .

 $('.posts-container').get("refresh_p.php", function(data){
          $(this).html(data);
          setTimeout(auto_refresh, 800);
 }).fadeIn();

Upvotes: 2

jgroenen
jgroenen

Reputation: 1326

Make sure your interval is long enough for your requests to finish. Also think about less real-time options, such as sending an array of messages every 15 seconds, showing them one after another on the client side. Optimize your server side for quick response using caching and also think about using json data and client side templating instead of html responses.

Upvotes: 0

Casey Dwayne
Casey Dwayne

Reputation: 2169

var auto_refresh = setInterval(function(){
    $('.posts-container').load("refresh_p.php").fadeIn(50);
},1000);

Changed the interval from 0 (which would just create a crazy load...) to 1000ms (1 second). Should work if your path is correct.

Upvotes: 0

Related Questions