Javascript – how to update content automatically without reloading webpage using php/ajax

ajaxhtmljavascriptjqueryphp

I'm trying to create an auction tool using PHP. The problem I'm having (and I appreciate its a basic one but I need clarification) is that I don't understand how to update the "auction price" automatically on each users screen without them having to take any action or without causing a full reload of the page.

So far I understand that Ajax is used to do this but if anyone could point me in the right direction or to any useful materials. My plan for my project so far is to use PHP and JavaScript so any solution would need to be compatible with these languages.

Note: I'm using a MySQL database.

Best Solution

Ther question you asked has so much possible answers, they could fill a whole book.

The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:

setInterval(function(){
$.get( "anyChanges.php", function( data ) {
  //do something with the returned data. Maybe update a table or something
});
}, 3000);

On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.

Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.

The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first: tutsplus tutorial

This library will be helpfull: socketo.me