Trying to get access to admin-ajax.php but failing
Sophia Terry
I’m having some trouble getting access to admin-ajax.php via admin_url and I get 400 Bad Request every time. Have looked at some posts in this forum but still can’t get why it’s not working.
My setup.php looks like this:
add_action('wp_enqueue_scripts', function () {
wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
wp_enqueue_script('sage/ajax-pagination', asset_path('scripts/ajax-pagination.js'), ['jquery'], null, true);
wp_localize_script( 'sage/ajax-pagination', 'sage', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
if (is_single() && comments_open() && get_option('thread_comments')) { wp_enqueue_script('comment-reply');
}
}, 100);And then I have added an ajax.js script which I will use and it looks like this:
$(document).on( 'click', '.nav-links a', function( event ) { event.preventDefault(); $.ajax({ url: window.sage.ajax_url, type: 'post', data: { action: 'ajax_pagination' }, success: function( result ) { alert( result ); } })
})So whenever I click the .nav_link I only get a "Failed to load resource: the server responded with a status of 400 (Bad Request) from localhost:3000/wp-admin/admin-ajax.php.
Does anyone have any idea what I’m doing wrong? Thanks in advance!
21 Answer
The reason you are getting a 400 (Bad Request) is beacause you are not adding 'nonce' in your ajax call.
When the console says "Failed to load resource: the server responded with a status of 400 (Bad Request) from localhost:3000/wp-admin/admin-ajax.php." it means it wasn't able to fetch the result back from the server. You are missing nonce which is very is necessary to fo the ajax request. Learn more about it here:
Your code should look like this.
wp_localize_script( 'sage/ajax-pagination', 'sage', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajax-nonce')
));and in your JS file.
$(document).on( 'click', '.nav-links a', function( event ) { event.preventDefault(); $.ajax({ url: window.sage.ajax_url, type: 'post', data: { action: 'ajax_pagination', nonce: window.sage.nonce, }, success: function( result ) { alert( result ); } })
})