Render an spinner


#1

Hi,

In my slim app i have a function that it takes a long time. My idea is to show an spinner first and then, when all function finish render my template. Why is the way to do this?

Something like this

public function inport($request, $response, $args) {

    // HERE FIRST SHOW THE SPINNER

    // THEN RUN MY CODE (it takes 2min)

    // AND FINALLY RENDER TEMPLATE WITH DATA
    return $this->view->render( $response, 'inportresult.html', $inportresult_data);
  }

Any idea?

Thanks,


#2

Hello @xpico,

Instead of one request, you can split it in multiple requests:

Request 1: /job/start: starts the job in the background and returns a page with a spinner and some javascript that regularly polls /job/status until the job is done. when the job is done, the javascript replaces the spinner with a “completed” message.
Request 2: /job/{id}/status returns the status of the job, e.g. running, done or error


#3

hi @llvdl,

Thank for your suggestion. You know any method to doing background jobs in easy way?


#4

You can use exec to start a another script in the background. If you use linux, you need to redirect the output to another file or stream (e.g. /dev/null or a log file) and add an ampersand (&) at the end of the command, to make it run in the background.

For example:

<?php
// generate a unique job identifier to monitor the job
$jobId = uniqid();

// run the job script in the background and pass the job id
exec('php job.php ' . escapeshellarg($jobId) . ' >/dev/null &');

print 'Job is started in background with id ' . htmlspecialchars($jobId) . PHP_EOL;

job_start.php

<?php
$jobId = $argv[1]; // get job id passed through command line

sleep(10); // do some heavy processing...

// job is finished, store this information in a file or database, so status can be polled.
$fh = fopen('finished.txt', 'a');
fputs($fh, $jobId . PHP_EOL);
fclose($fh);

job.php


#5

I would go to a page and inform the user about a longer running progress,
after a small period of time, then redirect to the long process and do it’s job.
As a result, render some statistics or something.