There is such a task: you need to make a progress bar to perform the function in php. there is such a cycle php

function new() { $url = " "; $html = curl_get($url); $dom = str_get_html($html); for ($i = 0; $i < 14; $i++) { $aux = $dom->find('h3.media-heading a', $i); // ищем название статьи $data['name'][] = $aux->plaintext; // записываем название статьи $data['links'][] = " " . $aux->href; // записывавем ссылку на статью $aux = $dom->find('div.article-info time', $i); // находим дату $str1 = $aux->plaintext; // обрабатываем $str1 = str_replace(' / ', ' ', $str1); // дату $data['date'][] = date("Ymd H:i:s", strtotime($str1)); // записываем дату $aux = $dom->find('span.icon-comments', $i); // находим количество комментариев $data['num_comm'][] = str_replace('"', '', $aux->plaintext); // записываем коичество комментариев $aux = $dom->find('span.icon-views', $i); // находим количество просмотров $data['num_views'][] = str_replace('"', '', $aux->plaintext); // записываем коичество просмотров } for ($i = 0; $i < count($data['links']); $i++) { $html = curl_get($data['links'][$i]); // переходим по $dom = str_get_html($html); // сылкам на $aux = $dom->find('div.pull-left a', 0); // статей и $data['article'][] = $aux->plaintext; // засисываем раздел $aux = $dom->find('div.field-items', 0); // выбираем содржание статьи и $data['content'][] = str_replace('&nbsp;', ' ', $aux->plaintext); // записываем } 

when you click on a button, a modal window should appear in which it is written: data collection has begun, and upon completion it should appear completed. Maybe someone will throw ideas on the implementation of ajax. Thank.

    1 answer 1

    Using AJAX is not entirely correct: the initiator should be the server, not the browser. For this, it is better to use web sockets: you do not need to constantly pull the server, and everything is operational. Web sockets with a bang are made on NodeJS, on PHP everything is very sad.

    On AJAX you can do this:

    • write a unique token to data and launch the action longaction.php
    • on beforeSend hang tickProgress = setInterval(progressBar, 1000);
    • in progressBar via AJAX, using the token, we get the current state. What is the PHP script done for ( tickprogress.php ) "they took a token, got into the database, sent a digit"
    • the interaction between the script, which does the work of longaction.php , and tickprogress.php - through any base, including memkes. I do not advise through the file.
    • when 100% is reached, we do clearTimeout(tickProgress)

    Example:

    HTML page index.html :

     <!DOCTYPE html> <html lang="ru-RU"> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ inProgress = false; $('.js-submit').on('click', function(){ // защита от повторного нажатия кнопки if(inProgress) return; inProgress = true; var tickProgress; var token = Math.random(); $.ajax({ data: { token: token }, url: '/longaction.php', // долгая операция beforeSend: function() { // запускаем получение прогресса console.log('beforeSend'); tickProgress = setInterval(function(){ $.ajax({ data: { token: token }, // скрипт получение прогресса по токену url: '/tickprogress.php', success: function(progressResp) { $('.js-progress').html(progressResp.progress); console.log(progressResp); } }); }, 1000); }, success: function() { // операция завершена console.log('success'); }, complete: function() { // сбрасываем получение прогресса в любом случае - успех, ошибка console.log('complete'); inProgress = false; clearTimeout(tickProgress); } }); }); }); </script> </head> <body> <button class="js-submit">Run</button> <p class="js-progress">--</p> </body> </html> 

    The script is a long operation longaction.php

     <?php // Скрипт долгой операции $token = (string)$_REQUEST['token']; $key = 'progress-' . $token; $fileName = '/tmp/' . $key; // Вариант с Memcache // $memcache_obj = memcache_connect('localhost', 11211); for($i = 1; $i <= 10; $i++) { // Вариант с Memcache // $memcache_obj->set($key, $i, false, 600); file_put_contents($fileName, $i); sleep(1); } $ret = [ 'token' => $token, 'success' => 1 ]; header("Content-type:application/json"); die(json_encode($ret)); 

    Getting the progress of a long operation tickprogress.php

     <?php // Получение прогресса долгой операции $token = (string)$_REQUEST['token']; $key = 'progress-' . $token; $fileName = '/tmp/' . $key; // Вариант с Memcache // $memcache_obj = memcache_connect('localhost', 11211); // $progress = $memcache_obj->get($key); $progress = file_exists($fileName) ? file_get_contents($fileName) : 0; $ret = [ 'progress' => $progress, 'token' => $token, 'success' => 1 ]; header("Content-type:application/json"); die(json_encode($ret)); 
    • I have an example with memkesh. Most likely you do not have it. Try using the MySQL table for storing progress: CREATE TABLE progress ( token CHAR (36) NOT NULL, value DECIMAL (5,2) NOT NULL, PRIMARY KEY ( token )) ENGINE = INNODB; Request to insert and update progress values: INSERT INTO progress ( token , value ) VALUES ('token-0.25202936938741116', 1) ON DUPLICATE KEY UPDATE value = 1; Request for status: SELECT value FROM progress WHERE token = 'token-0.25202936938741116' LIMIT 1; - Total Pusher
    • $ token = (string) $ _ REQUEST ['token']; here the token parameter is not passed - user286428
    • var token = Math.random(); - it is created in JS, and it must be passed to both PHP scripts. - Total Pusher
    • $ .ajax ({data: {token: token}, here is the transfer, but the data on the php side is not accepted - Vladimir
    • 1. Look in the Chrome console, Network tab - is the token transmitted via the XHR. 2. It is possible that your framework changes $_REQUEST , then the request data must be obtained by means of the framework. 3. This is a minimal working example, try it first. In the example, the script writes directly to the disk, it is unsafe. Project on githabe - Total Pusher