I’m trying to make a simple ajax call to update html of my template. I’m new to wordpress and sage and couldn’t find a comprehensive explanation of how to make ajax calls anywhere. So if my code doesn’t make any sense that’s why. Right now the ajax should return a hardcoded response string that says ‘it works’ and paste it inside the div. But success never happens because I think I can’t get my js to point to my ajax.php. Here is my code:
main.js
document.getElementById('one').addEventListener('click', () => {
jQuery.ajax({
action: 'filter_listings',
data: 'category = 3',
method : 'POST',
url : 'ajaxObject.yourAjaxURL',
success: function(result){
$('#posts_list').html(result);
},
});
})
setup.php
add_action( 'wp_ajax_filter_listings', 'App\Controllers\Ajax::filterListings' );
add_action( 'wp_ajax_nopriv_filter_listings', 'App\Controllers\Ajax::filterListings' );
Ajax.php
<?php
namespace App\Controllers;
use Sober\Controller\Controller;
use Roots\Sage\Assets;
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
wp_localize_script( 'sage/main.js', 'ajaxObject', [ 'yourAjaxURL' => admin_url( 'admin-ajax.php' )]);
class Ajax extends Controller
{
function filter_listings()
{
$filters = $_POST['filters'];
$name = \App::changeposts2($filters);
wp_send_json('it works');
}
};
app.php This is completely bypassed since I hardcoded the response on the last file to ‘it works’
$args = array(
'orderby' => 'title',
'per_page' => 10,
'categories' => 2,
);
$url = add_query_arg( $args, 'https://localhost/bedrock/web/index.php/wp-json/wp/v2/posts');
$stuff = wp_remote_get($url, array('sslverify' => FALSE));
$body = wp_remote_retrieve_body($stuff);
$posts = json_decode($body);
$response = \App\template('partials.comments', ['posts' => $posts]);
return 'it works';
}