1

is there a better way to use jquery and php to help check for messages like inbox etc. i know i can use the ajax with set interval to check for a particular php file giving me the messages

something like this with set interval

$.ajax({
    url: "message.php",
    type: "POST",
    data: { time : time_stamp },
    dataType: "json",
    success: function(data) {

                  // update the div content from here

        }
    }
});

but is there a better way of doing this because with set interval say like 10 minutes each and say if a user spends 8 minutes on a page and goes to next page , the interval starts all over again instead of 2 minutes .

so i was wondering if its possible to trigger a ajax request using something like php cron jobs or something of that sort to better handle this case .

cheers guys :)

mega-crazy
  • 838
  • 2
  • 17
  • 36

2 Answers2

1

You could use long polling to keep a connection open until either a message is available or a time limit is reached.

Basically you just give your Ajax call a long timeout and have your server-side script simply not respond until a message is available. Your client will hold the connection open until the timeout, then have it open the connection again. You will get instant feedback at the cost of having to maintain an open HTTP connection. It is also supported by all browsers.

See this answer for an example and more in-depth explanation: How do I implement basic "Long Polling"?

Community
  • 1
  • 1
nullability
  • 10,545
  • 3
  • 45
  • 63
0

In my opinion, WebSockets would be a great way to implement this. This gives you real time client/server interaction. Not all browsers support this yet, but you can get client-side libraries that fallback to long polling automatically if the browser doesn't support it. Socket.io is one such library and a good client-side library for web sockets. I've never done a web sockets server using PHP, but I imagine there are good options out there for this too.

Kyle
  • 4,261
  • 11
  • 46
  • 85