Hello guys,
Im wondering if this is the right way to use Ajax with sage 10:
app/ajax.php:
<?php
namespace App;
class Ajax
{
public function __construct()
{
add_action('wp_ajax_my_posts', [$this, 'my_posts']);
add_action('wp_ajax_nopriv_my_posts', [$this, 'my_posts']);
}
public function my_posts()
{
$catName = $_POST['category'];
$ajaxposts = new \WP_Query([
'post_type' => 'post',
'posts_per_page' => -1,
'category_name' => $catName,
'orderby' => 'menu_order',
'order' => 'desc',
]);
$response = '';
if ($ajaxposts->have_posts()) {
while ($ajaxposts->have_posts()) : $ajaxposts->the_post();
$response .= \Roots\view('partials.list-item');
endwhile;
} else {
$response = 'empty';
}
echo $response;
exit;
}
}
new Ajax();
Resources/scripts/app.js
/* Ajax call */
(function ($) {
jQuery(function ($) {
$('.cat-list_item').on('click', function () {
$('.cat-list_item').removeClass('active');
$(this).addClass('active');
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'my_posts',
category: $(this).data('slug'),
},
success: function (res) {
$('.project-tiles').html(res);
},
});
});
});
})(jQuery);
I then added ajax to collect array in bootstrap/app.php
It works fine but, Im i doing it the right way ?
Thanks