How to use Ajax with CakePHP using jQuery
With this post, I am going to explain how to make AJAX calls using jQuery in cake php. Effective posting related to this topic is very rare. Cake php is a PHP framework designed using MVC pattern. You have model, controller and view. In the cake php layout page, normally you add the fallowing code somewhere in the page.
After executing the controller funcitons, the relavent view *.ctp file will be rendered where you have placed above code inside the layout page. If you consider blog example, after executing PostsController's view() action, view.ctp file will be rendered. This is the default behaviour of cake php. But, you may need more control when rendering view files in cake php than the above default behaviour. Sometime, you may need to load the relavent view file's contents into a spacific DIV tag in currently rendered page without refreshing the page. In this case, you may need AJAX support with cake php. I will explain how to do this with cake php. And also, I am going to explain how to get JSON response from cake php's controller function and update some contents of the page with javascript function. I am going to use jQuery support for this functionality. To have jQuery support for my cake php project, I include the fallowing in my laytout page.(This layout may be default.ctp or your own another layout page).
The above line links 'jquery-1.3.2.js' file to my layout page.
Now, you we have jQuery support for our business. But not all. jQuery has sevaral UI supports. Next, we will start the real task. I am going to create the client side javascript function that makes AJAX request to cake php controller's action.
I am going to create Post data view function(Think about cake php blog example) with ajax support. Post title will be listed as links, and when user clicks on link, the relavent post information will display in a DIV tag somewhere in the same page.
<a href="#" onclick="viewPost(<?php echo $post['Post']['id'];?>)">
<?php echo $post['Post']['title'];?><br/>
</a>
<?php endforeach; ?>
$posts is a variable defined in a controller before rendering this page.
The above code shows how to create list of links using cake php. When click on each link, viewPost() function will be called and relavent post id will be passed into that function. The viewPost() function will take the responsibilities to make the AJAX request to cake php action and subsequently update the page contents.
The javascript code for the viewPost() function as fallows.
function viewPost(postId){
var data = "id="+ postId;
$.ajax({
type: "post", // Request method: post, get
url: "/cake/index.php/posts/view/", // URL to request
data: data, // post data
success: function(response) {
document.getElementById("post-view").innerHTML = response;
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
}Next, we will explore the server side code for the view action in cake php controller. The code as fallows.
function view($id = null) {
Configure::write('debug', 0);
if($id == null){
$id = $_POST["id"];
}
$this->pageTitle = 'View Post';
if($this->RequestHandler->isAjax()) {
$post = $this->Post->findById($id);
$this->set('post', $post);
$this->layout = 'ajax';
$this->render('view');
} else {
$post = $this->Post->findById($id);
$this->set('post', $post);
$this->layout = 'post_layout';
$this->render('view');
}
}
When the request is ajax, /app/views/posts/view.ctp file's content will be passed to the client as normal text/html. Then from the client side, "success" callback function will get this response and update the client page. If the request is normal request,/app/views/posts/view.ctp file will render in default cake php's behaviour, where you have placed <?php echo $content_for_layout; ?>.
function viewPost(postId){
var data = "id="+ postId;
$.ajax({
type: "post", // Request method: post, get
url: "/cake/index.php/posts/view/", // URL to request
data: data, // Form variables
dataType: "json", // Expected response type
success: function(response) {
var sb = [];
sb[sb.length] = "Title :" + response.data.title + "";
sb[sb.length] = "Body :" + response.data.body;
document.getElementById("post-view").innerHTML = sb.join("");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
}
Next we will see the server side code, which makes the json response.
function view($id = null) {
if($id == null){
$id = $_POST["id"];
}
$post = $this->Post->findById($id);
$this->set('post', $post);
$this->pageTitle = 'View Post';
if($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
$post = $this->Post->findById($id);
$this->layout = 'ajax';
$this->autoLayout = false;
$this->autoRender = false;
$this->header('Content-Type: application/json');
$data = array();
$result = array();
$data = array('title' => $post['Post']['title'],
'body' => $post['Post']['body']);
$result['status'] = "success";
$result['data'] = $data;
echo json_encode($result);
return;
} else {
$this->layout = 'post_layout';
$this->render('view');
}
}