Well, I am new to CakePHP. So a painful day to debug this. Here are my code:
templates_controller.php
function reajax($id = NULL) {
$this->layout = false;
$this->Template->id = $id;
$template = $this->Template->read();
$this->set('result', $template['Template']['content']);
}
reajax.ctp
echo $result;
js file
$(document).ready(function() {
$(".abcd").click(function(event){
event.preventDefault();
var id = this.id;
$.ajax({
type:"GET",
url:"/templates/reajax/" + id,
success : function(data) {
alert('success');
$("textarea").text(data);
},
error : function() {
alert(id);
},
})
});
})
The click file
<ul class="content-box-tabs">
<?php echo $html->link($html->image('thumbnails/'.$template['Template']['thumbnail'], array('alt' => 'test', 'height' => '120', 'width' => '110')), array('controller' => 'templates', 'action' => 'reajax'), array('class' => 'abcd', 'id' => $template['Template']['id'], 'escape' => false))?>
</ul>
Every time I get a error result, and I have no idea what's wrong with my code. Can anyone help me? Thanks in advance.
Everything is going well when I edit the JS file below. I don't know if this is a bug of CakePHP or if there is something else wrong with my code. I need a spider man!
$(document).ready(function() {
$(".abcd").click(function(event){
event.preventDefault();
var id = this.id;
$.ajax({
type:"GET",
url:"/cakephp/templates/reajax/" + id,
//url: "/templates/reajax/" + id,
success : function(data) {
alert('success');
$("textarea").text(data);
},
error : function() {
alert(id);
},
})
});
})
not sure about this string
$this->layout = false;
create new empty layout ajax.ctp like this
<?=$content_for_layout?>
and try to use it
$this->layout = 'ajax';
and.... you can try to use this way for ajax request
$.get('/controller/action/'+Math.random(),{},function(data){
$('#result').html(data);
});
The reason you get an error always is because you are never returning a response from the action you have to do an echo of a json for instance, you are simply setting the data and that's it.
You should also have some kind of validation in your controller method, what happens if the template with the provided ID does not exist? You will get an error and are not handling it.
first of all you should echo your result then exit your function or make it autoRender = false; for debuging you should use developers tool.
1.$this->autoRender = false;
or $this->viewBuilder->layout('ajax');
(for Cakephp 3.0 & make a ajax.ctp inside layout folder) ajax.ctp
should look like
<?php
echo $this->fetch('content') ;
?>
You don't need to make the .cpt for ajax function because ajaxFunction could return some value not the html.
Then you can check it's ajax request or not .(It is not essential for best practices)
if ($this->request->is('ajax')) {
// do your logic here
}
Now your code should look like this
function reajax($id = NULL) {
$this->autoRender= false;
$result = "Some value";
echo $result;`enter code here`
}
It will help you.