Changes
Title
unchanged
Background task with Ajax
Category
unchanged
Tutorials
Yii version
unchanged
Tags
unchanged
background, asynchronous, AJAX
Content
changed
[...]
// Returned from the form
if (isset($_POST['par'])) {
$par = $_POST['par']; // parameter specified
$fn = "rep_$par.txt"; // file name
$mime = 'text/plain'; // file type
$cont = $model->doTask($par); // generate reportlong report generation
// Ajax button
if (Yii::app()->request->isAjaxRequest) {
$lt = new Longtask;
$lt->cleanMy(); // deletes the previous task
result
$lt->filename = $fn;
$lt->cont = $cont;[...]
### runTask form
This form contains one text field, a submit button and an ajaxSubmitButton. The same form contains also
thea link to download the result of the executed background task:[...]
* The application administrator should have access to the `longtask` table in order to monitor all the background jobs.
* One can use also [`ajaxLink
`](http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxLink-detail) in case there are no input parameters requested from the user.
* One can keep more records per task/user to preserve the history of tasks. In this case it is better for the user to have access to the `longtask` table via [
`CGridView
`](http://www.yiiframework.com/doc/api/1.1/CGridView).
* More information on the tasks can be specified in the `longtask` table. For example, it is possible to save the start time and the percentage of the execution. See for example the [BackJob extension](http://www.yiiframework.com/extension/backjob/).[...]
* When the task's result is downloaded, it is reasonable to automatically delete the task's record from the `longtask` table. When the user has downloaded/deleted from the `runTask` form, a javascript should immediately hide the download link.
* When the task takes very long time to execute, it is a good idea to add in the beginning of the task code the `set_time_limit()` PHP instruction.