Summary of tips for creating websites using Ajax and JSON with cakePHP

A0002 001091

Good evening, this is Bono.

I've never really used frameworks before, but I want to continue to learn about rapid development and such, so I decided to give it a serious try.

I will keep this as a reminder and summary so that the next time I see it, I won't have to look up the same thing again.

  • CSS: Using Bootstrap
  • Framework: cakePHP is used
  • Database: MySQL used
  • Development: vim use
  • Server: AWS from localhost
  • API: Using Google Maps API
  • Data receipt: JSON

Put Bootstrap in the designated folder.

I took the following method of manually putting files into the img, js, and css folders.
It's easy, just put it in the Plugin folder.

Notes on the process of changing CakePHP design to Twitter Bootstrap | asklife

Memorandum in Controller

Prepare the database to be used within the class.

public $name = "Main"; //使用するコントローラの名前を宣言
public $uses = array('Question', 'Answer', 'User'); //使用するデータベースを指定
public $autoLayout = false; //指定しないとdefault.ctpが適用される
public $autoRender = true; //trueにしないとレンダリングしてくれない
public $helpers = array('Js' => array('Jquery')); //ヘルパーを指定
public $components = array('RequestHandler'); //Ajaxを使う時に必要みたい

It seems to be necessary when exchanging data in JSON format.

public function beforeFilter(){
    if($this->RequestHandler->isAjax()){
        if($this->action =='getAjaxAnswer'){
            Configure::write('debug', 0);
            $this->RequestHandler->setContent('json');
            $this->RequestHandler->respondAs('application/json; charset=UTF-8');
        }
    }
}

How to pass values to the view. Use $this- >set().
Question is the name of the database. find('all') retrieves from all columns.

When specifying conditions, use find('all', array('conditions'= > hoge)).

public function hoge() {
    Configure::write('debug', 0); //デバッグを無効に。有効にする時は1
    $dataOfQuestion = $this->Question->find('all');
    $this->set('dataOfQuestion', $dataOfQuestion);
}

When saving data, use $this- >save().
If you want to include the time, use date('Y-m-d H:i:s'), etc.

public function addRecord() {
        $this->Question->data['Question']['created_at'] = date('Y-m-d H:i:s');
        $this->Question->data['Question']['place_lat'] = const;
        $this->Question->save($this->data);
}

When passing data to the view in JSON format, use the following method. json_encode

    return new CakeResponse(array('body' => json_encode(array(
        'content'=> $dataOfQuestion[$dataNumber]['Question']['content'],
        'level'=> $dataOfQuestion[$dataNumber]['Question']['level'],
        'qid'=> $dataOfQuestion[$dataNumber]['Question']['qid']
    ))));

When retrieving data from a database for a certain condition

    $selectedQuestion = $this->Question->find('all', array(
        'conditions'=> array('Question.qid' => $qid)));

Other

I'll come back to views, databases, and the whole thing in the next issue.