简体   繁体   中英

cakephp refresh view from controller

I'm new to CakePHP. Supposed to be a simple task, but I run into problems. I have a controller that puts records into the database from traversing a given directory - all goes well. Now in the view, I want to display the progress of the operation (there are thousands of records, so it will last some time).

I already have a counter ( $countFound , $countSaved , $countDiff ) in the controller and set these to output in the view, but it isn't updating. I tried

$this->Session->setFlash()

from within the loop, but these flashes get displayed only once the operation has completed.

You will need to use Javascript and Ajax with some custom methods in your controller to simulate RealTime update in your view.

Try using Jquery's ajax method to check periodically if there's a new record (setInterval + $.ajax wich will provide the last displayed record to the custom controller method, the controller method check if there's any new records if so it returns it or nothing, meanwhile in Jquery's ajax callback process the result of the controller method and display the records if there's any)

something like this

    setInterval(function(){
      $.get(url, {lastrecordID:_id}, function(data){
        if(data !== "undefined") // append to the dom 
             dom.append(data).fadeIn();
      });
    },250);

url, _id and dom are js data that you should fill dynamically depending on the context.

If you want the only show the number of records then ask for the new records each xx millisecond and update the field

var dom = $('.directoriesCount');
setInterval(function(){
          $.get('directories/countupdate', {}, function(data){
            dom.empty().append(data);
          });
        },250);

And in Directories controller :

public function countupdate() {
    return $this->Directory->find('count');
}

I didn't take performance into account, so if the view containing is frequently used you might want to optimize the count query or increase the interval between updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM