Implement a long survey using jQuery and PHP

I want to create a chat based on JavaScript (jQuery will be used for AJAX) and PHP.

I heard that a good way to do this is to use a lengthy survey.

I understand this idea, but I do not know how to implement it on the server side.

An endless loop sounds like a bad idea.

+4
source share
2 answers

You do not want to create an infinite loop, but you can set a timeout. Basically, a loop for X-second waits for some data, and if this does not happen, send a response to the client stating that he needs to initiate a new request that will have the same timeout period.

$source; // some data source - db, etc $data = null; // our return data $timeout = 30; // timeout in seconds $now = time(); // start time // loop for $timeout seconds from $now until we get $data while((time() - $now) < $timeout) { // fetch $data $data = $source->getData(); // if we got $data, break the loop if (!empty($data)) break; // wait 1 sec to check for new $data usleep(10000); } // if there is no $data, tell the client to re-request (arbitrary status message) if (empty($data)) $data = array('status'=>'no-data'); // send $data response to client echo json_encode($data); 
+7
source

implementing this type of chat is not a good idea in php, you can use CometChat , Nodjs , and if you can’t install scripts on your server, than use the available APIs to send real-time data,

e.g. Pubnub , Pushemr , Beaconpush .

0
source

Source: https://habr.com/ru/post/1440087/


All Articles