I'm new to PHP. I'm going to make a simple web application using PHP, a chat box.
I don't know a better way to refresh the chat window as soon as new msg received. The only thing that comes into my mind is refreshing page frequently. I know it's not a good idea.
I know how to use AJAX, so I can refresh only the chat box (without refreshing whole page). But in AJAX also, client has to send a request.
Is there a way to refresh the chat box by the server when a new msg received?
The standard communication order in web applications is that HTTP requests are initiated by the web client (browser) and then responded by the server.
What you would need is that the roles are reversed and the server machine requests the client machine to receive a message.
This is called a server push. The linked Wikipedia article lists a lot of workarounds.
The client repeatedly asking the server if a new message has arrived is the simplest method, it is called polling, but done with a high frequency puts stress on the server (multiplied if several clients do this) and with a low frequency is not responsive enough for many use cases.
Despite the big font used by fellow user emsch, WebSockets are not feasible for everyone (yet), as not every browser supports it. Compare your browser/os matrix e.g. with browser implementation.
My favourite a couple of years ago was BOSH, which I preferred to other methods like Comet: BOSH needs a connection held by the server for the server to be responsive and a potential second connection to the server for the client to be response. As timeouts can happen, empty exchanges are performed with a low frequency after some time. So if no messages arrive at the server or client, BOSH behaves like a slow polling.
If you are new to web and network development I would suggest to look for a nice messaging library.