javascriptjsoncordovacakephpcakephp-2.6

Loading the views of Cakephp and send them to my Phonegap Project


I am working on an application using Cakephp 2.6.0 on the server side and PhoneGap 5.4.1 at the client Side, with JSON as an intermediate to access the server side.

I would like to ask if is it possible to load the content of the views, send them to the client side using JSON and display them using JavaScript? if yes, how can I do it? Any help would be greatly appreciated.


Solution

  • I think the best way is to use your Cordova / PhoneGap Application as your client side (view) and CakePHP as server side (model and controller). From your PhoneGap Application you can communicate for example via ajax to your CakePHP application to share data or do some CRUD operations.

    I try do give some inspiration and show you how u can get user data by passing the userId from your cordova application to cakephp:

    IMPORTANT: I have skiped the authentification part in this example. For more information see CookBook 2.x - Authentification

    Cordova / Phonegap:

    document.addEventListener('deviceready', onDeviceReady, false);
    
    function onDeviceReady() {    
    
       $.ajax({
          url : 'www.yourUrl.com/YourAppName/users/view/1', // 1 => userId
          data : {},
          dataType : 'json',
          success : function(result) {
             // do something with the result
             // e.g. access user name: result['User']['name'];
          },
          error : function(xhr, status, err) {
             // do something on error
          }
       });
    }
    

    CakePHP:

    class UsersController extends AppController {
    
        public $name = 'Users';
    
        public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('view');
        }
    
        public function view($userId = null){
            $this->autoRender = false;
    
            // use $this->Auth->User('id') insted of $userId 
            // as soon as you have implimented the user authentification
            $user = $this->User->findById($userId);
            echo json_encode($user); 
            die;
        }
    }
    

    Edit:

    If you want to get the view content as json take a look at this example from derEuroMark blog. He has created a AjaxView that takes care of mapping the content into a JSON structure, and automatically tries to render just the simple HTML template code in the ctp via "ajax" subfolder (View/ControllerName/ajax/favorites.ctp). Link: AjaxView