Issue
I've used AJAX a lot in PHP, but now I'm trying to learn CakePHP, and haven't been able to ANY good/simple examples of how to use AJAX with CakePHP 1.3. The only examples I've been able to find are for paging (not what I need), or use the deprecated helpers while forcing you to include scriptaculous or prototype.
Are there ANY good/simple examples of how to use AJAX w/ CakePHP 1.3? Or is it something someone could explain here?
All I want to do is have the user click a link, which retrieves the contents of a php file, and inserts it into a div. The contents of the php file would be altered based on some POST or GET variables sent w/ the ajax call. Seems simple enough :(
Solution
This is the pattern that I use in CakePHP 1.3.x. The process is generally:
- Creating alternative json-oriented layout and view files
- Detecting if the incoming request is AJAX
- Explicitly rendering the alternative json layout/view instead of text/html
Be sure to include RequestHandler component and JsHelper in your app controller.
In a given controller:
function test() {
if($this->RequestHandler->isAjax()) {
$this->set('data', $this->data);
// Explicit call to render an ajax response, using a layout and view made specifically for ajax
$this->layout = 'json';
$this->render('ajax_test');
}
// else render views/controllername/test.ctp like normal
}
Your app/views/layouts/json.ctp file:
<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: text/x-json');
header("X-JSON: ".$content_for_layout);
echo $content_for_layout;
?>
Your app/views/controllername/ajax_test.ctp file should contain only:
<?php echo $js->object($data); ?>
Now, on your page that's actually going to make an ajax call, it might look something like this, with jQuery code:
<div id='status'></div>
<?php echo $form->create('Test', array('id'=>'testForm')),
$form->input('message'),
$form->end();
?>
<script type='text/javascript'>
$('#testForm').submit(function(event) {
event.preventDefault(); // interrupt form submission
$.ajax({
type: "POST",
url: "/controllername/test",
data: $('#testForm').serialize(),
success: function(data, textStatus, xmlHttpRequest) {
$("#status").html(data.Test.message);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("There was a problem processing the request: " + jqXHR);
}
});
});
</script>
Answered By - Tyler
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.