jQueryでAjaxしたメモ。
こちらを超参考にさせていただき、やってみたメモ。
CakePHPでjQueryを使ってAjaxする方法 | IDEA*IDEA
ビューにてJavaScriptをかく。
<div class="clearfix"><label for="product_new_id">商品IDを指定して追加して下さい。</label> <div class="input"> <input type="text" id="product_new_id" class="span2" maxlength="50" placeholder="商品ID"> <button class="btn" id="add_product_button" type="button">追加</button> </div> </div> <table id="product_list"> <thead> <tr> <th>商品ID</th> <th>商品名</th> <th>価格</th> <th> </th> </tr> </thead> <tbody></tbody> </table> <?php echo $html->scriptStart(array('inline' => true, 'safe' => true)); ?> $(function(){ $("#add_product_button").click(function(){ // action_urlは、UserDirで動かしたりadminルーティング用に、 // controllerで$_SERVER['REQUEST_URI']を使って組み立ててsetしといた。 $.post( '<?php e($action_url); ?>', { 'product_id' : $("#product_new_id").val() }, function(response){ //console.log(response); $("#product_list > tbody").prepend(response); } ); }); }); <?php echo $html->scriptEnd(); ?>
コントローラでアクションを実装。
<?php function add_product() { // デバッグ情報の出力を抑制 Configure::write('debug', 0); $this->layout = 'ajax'; if ($this->RequestHandler->isAjax()) { // postデータはparams['form']に入っている。 $id = $this->params['form']['product_id']; if(!is_numeric($id)) { exit(); } $product = $this->Product->find( 'first', array( 'conditions' => array( 'Product.id' => $id, ), 'recursive' => -1, ) ); if($product != false) { $this->set('id', $id); $this->set('name', $product['Product']['name']); $this->set('price', $product['Product']['price']); } else { exit(); } } }
Ajax用のビュー(add_product.ctp)。
<?php setlocale(LC_MONETARY, 'ja_JP'); ?> <tr><input type="hidden" name="data[Product][id][]" value="<?php e($id); ?>"> <td><?php e($id); ?></td> <td><?php e($name); ?></td> <td><?php e(money_format("%!.0n",$price)); ?>円</td> <td><?php echo $form->button('削除', array('type' => 'button', 'class' => 'btn', 'escape' => false, 'onclick' => '$(this).parent().parent().remove();')); ?></td> </tr>
できたー。