I use Cakephp 2.8.0. My problem is ajax. I don't know how realize ajax in my application. I have li links with categories and after click i need delete some html code and find in my controller necessary category and get this array in response html and print it.
my PhotosController action:
public function getPhotoByCategory($category = null)
{
$category=$_GET['category'];
debug($category);
$this->render('getPhotoByCategory', 'ajax');
}
My html code:
<div class="lol">
<ul>
<?php foreach($categories as $category):?>
<li>
<a href="<?php echo $category['Category']['cat_name'];?>" class="lol"><?php echo $category['Category']['cat_name'];?></a>
</li>
<?php endforeach;?>
</ul>
</div>
My JS code:
$(".lol").click(function (e) {
e.preventDefault();
var category = $(this).attr("href");
$.ajax({
type: 'get',category,
data: {catyegory:
url: '<?php echo $this->Html->url(array('controller' => 'Photos', 'action' => 'getPhotoByCategory')); ?>',
success: function(response) {
if (response.error) {
alert(response.error);
console.log(response.error);
}
if (response.content) {
$('#target').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
Please, help me with right ajax in cakephp for this situation.
I find the best way to handle AJAX for fetching items is to create an element of the items you want to insert (in your case photos from a category).
PhotosController.php
public function getPhotoByCategory($category = null)
{
$this->set('photos', $this->Photo->find('all', ['conditions' => ['category_id' => $category]]);
$this->render('Elements/getPhotoByCategory');
}
The element in the above example contains a for loop that loops through $photos and outputs them. This is then loaded into the div "lol" using the JS code down below:
Views/Photos/get_photo_by_category.ctp
<button class="loadphoto">Load Photos</button>
<div class="lol">
</div>
JS Code (top of view?)
$('.loadphotos').click(function(e) {
$('.lol').load('/Photos/getPhotoByCategory/1')
.fail(alert("error"));
});
Dereuromark has done some decent documentation on AJAX and CakePHP