You are using ajax .. the whole concept of ajax does not require a page reload ...
The best tools for the job:
- WebSockets Less overhead. Two way communication. disadvantage: itβs more difficult to implement and not navigate through the browser.
- events sent by the server. Less overhead. One way communication, no repeated requests. flaw: not cross browser
- just a simple ajax poll ... less efficient, more overhead, lots of requests, but it will work everywhere.
Socket.io (written for nodeJS) is probably the best for work. It uses the correct transport (websockets, longpolling, server-sent events, flashsockets, ajax polling) for you and will give you better performance.
The following are examples of PHP php js examples:
using DOM events sent by the server ( not cross-browser ): +/- updates every 3 s
//javascript: var source = new EventSource('updates.php'); source.onmessage = function (event) { console.log(event.data); }; //php server side: <?php header("Content-Type: text/event-stream\n\n"); //..perform queries and put it in $data.. echo "data: " . json_encode($data) . "\n"; ?>
using jQuery ajax request: will send a request every 1000 ms
//javascript: var interval_id = setInterval(function(){ $.ajax({ type: "POST", url: "updates.php", success: function(data){ console.log("Data: ", data); } }); }, 1000); //last param is the interval time in ms //php server side: <?php //..perform queries and put it in $data.. echo json_encode($data) . "\n"; ?>
using phpWebsockets: lib + codeample
Vdp
source share