目次

jQueryで非同期処理(DB更新)

テーブル作成

CREATE TABLE IF NOT EXISTS `tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
);

index.ctp

<?php
echo $html->script('jquery-1.3.2.min', array('inline' => false));
echo $html->script('jquery-ui-1.7.3.custom.min', array('inline' => false));
?>
<h2>Tasks</h2>
<?php
echo $form->create('Task', array('default'=>false));
echo $form->input('title');
echo $form->submit('Add');
echo $form->end();
?>

<ul id="tasks">
<?php foreach($tasks as $task) { ?>
<li><?php echo h($task['Task']['title']); ?></li>
<?php } ?>
</ul>
<script language="JavaScript">
$(function() {
    $("#TaskIndexForm").submit(function() {
        $.post('/tasks/ajax_add', {title: $("#TaskTitle").val()}, function(rs) {
            $("#tasks").prepend(rs);
            $("#TaskTitle").val('').focus();
        });
    });
});
</script>

ajax_add.ctp

<li><?php echo h($t); ?></li>

ajax.ctp

<?php echo $content_for_layout ?>

tasks_controller.php

<?php
class TasksController extends AppController {
    var $name = 'Tasks';
    var $components = array('RequestHandler');
    var $layout = 'Tasks';

    function index() {
        $this->set('tasks', $this->Task->find('all'));
    }

    function ajax_add() {
        $this->layout = "ajax";
        if($this->RequestHandler->isAjax()) {
            $title = $this->params['form']['title'];
            $this->Task->id = null;
            $this->data['Task']['title'] = $title;
            $this->Task->save($this->data);
            $this->set('t', $title);
        }
    }
}