Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Trying to get access to admin-ajax.php but failing

Writer 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!

2

1 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 ); } })
})

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy