How can I check if a new entry is added to the table, then make a request?

That is, the client has sent a message to add to the database.

In the consultant window we make a request to the database. We pull the sent message from the client .

I know the option to send a request to the database every second through Settimeout, ajax. But I think this will create a lot of problems because of the many requests that seem to block the site.

  • Blocking the site depends on the hosting. For example, the timeweb rate is highly dependent on the load on mysql. - ilyaplot

2 answers 2

You can make ajax request via setInterval, or use web sockets.

In order not to make each ajax request a connection to the database, and even more so the request, create a text file and keep in it the date of the last changes in the database. The PHP script that will respond to the ajax request must, before connecting to the database, read the date of the last file change and compare it with the one that came in the ajax request (you will have to store this number on the client side). If the time is the same, give the Last-Modified header and nothing else, $ .ajax is able to respond to such headers correctly (see ifModified). If the time is different, go to the base.

    Recently gave an answer to a question on this topic: How to connect changes on the site when a change in the database?

    In short, PHP itself is not intended for such tasks. Dances with intervals and ajax , are currently considered obsolete, WebSockets are ideal for your task ( https://habrahabr.ru/post/79038/ ). However, it is often necessary to prescribe scripts for cases when web sockets are not available for any (often independent of you) reasons, and prescribe a failback in ajax .

    @ilyaplot suggested a good method of checking for changes before throwing a query into the database. In any case, the interval should be set less often than every second (I think that once in 10-15 seconds it will be normal).

    • I usually applied the proposed method in cases where the web sockets were like a sparrow cannon. Even 2-3 requests per second showed a normal result and did not give a significant load on the server. True, I sent the request directly to the file, and in the case of isModified I sent the request to the php script and turned off the handler for a second or two. - ilyaplot
    • But today, of course, the most "fashionable" version - Angular + Websockets - ilyaplot
    • I think I will not zamarachivatsya just put on the interval. I thought there is some easy way - Sauron