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);
},
})
});
})
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With