-3

i am working on a Cakephp 2.x ....actually what i want is i am showing a battery level on my view page and memory usage too... so the battery and memory is keeps on changing after some seconds or minutes ... so i dont want user to refresh or reload the page evry time and checks the status of these two ... so i want to get the data from db in ajax or jquery and show them to the user ... i know the syntax of sending form data and then return in ajax ... but here i am not sending anything .. there are other things too on my page in which i need a data in ajax ... help me ... if anyone has implemented this before then please share it

mynameisjohn
  • 175
  • 1
  • 9
  • 31

1 Answers1

0

In the controller do your logic and then return an ajaxResponse.

  class FooController extends AppController{
    public $components = array("RequestHandler");
    //... Other actions here

    public function getSysParams(){  
         if($this->RequestHandler->isAjax()){
             //Your logic here, example:
             $sysInfo = $this->Foo->find('first', array('fields'=>array('battery', 'cpu'));
             //Return the data to AJAX call using json_encode
             return new CakeResponse(array('type' => 'application/json',
                'body' => json_encode(array('battery' => $sysInfo['Foo']['battery'], 'cpuUsage'=>$sysInfo['Foo']['cpu']),
                JSON_FORCE_OBJECT),
                'charset' => 'UTF-8')
             );

         }
     }
   }

And then in the js it will come like this:

{'battery':"33%", 'cpuUsage':"80%"}

I've tested it on CakePHP 2.3 and it works. On previous versions I'm not sure.


EDIT

This is the JavaScript part using jQUery:

       $.ajax({
         url: '/Foo/getSysParams'
         data: {'foo': 'bar'}, //Any data you want to send
         success: function(dataReturned){
             $("div#update").text(dataReturned.battery);
             $("div#update2").text(dataReturned.cpuUsage);
         }
       });
Pedro Tanaka
  • 48
  • 1
  • 7
  • i am not sending anything from the view page to this controller ? so is your function works ? i mean how the view page know that i have to call this function ...or how controller knows that i have to send the response to this view page – mynameisjohn Jul 20 '13 at 07:26
  • The page uses JavaScript to send a request to that controller/action, which does the backend logic and returns the values that the page's view needs to display. – Derek Jul 21 '13 at 01:48
  • I've updated the answer with the JS part. Please mark as correct! – Pedro Tanaka Sep 06 '13 at 19:17