I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.
Custom Page Template index.php
add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}
blogcontent.php
function myblog_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
echo $fruit;
}
die();
}
add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );
Ajax.Js
jQuery(document).ready(function($) {
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: myblog_ajax_obj.ajaxurl,
data: JSON.stringify({
'action': 'myblog_ajax_request',
'fruit': fruit,
'nonce': myblog_ajax_obj.nonce
}),
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
dateType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.
Custom Page Template index.php
add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}
blogcontent.php
function myblog_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
echo $fruit;
}
die();
}
add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );
Ajax.Js
jQuery(document).ready(function($) {
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: myblog_ajax_obj.ajaxurl,
data: JSON.stringify({
'action': 'myblog_ajax_request',
'fruit': fruit,
'nonce': myblog_ajax_obj.nonce
}),
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
dateType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
Share
Improve this question
edited Jul 21, 2020 at 17:12
mozboz
2,6281 gold badge12 silver badges23 bronze badges
asked Jul 21, 2020 at 12:16
JPLJPL
1372 silver badges11 bronze badges
3
|
3 Answers
Reset to default 3There's only one reason you get a 400 error with admin-ajax.php: The wp_ajax_{$action}
or wp_ajax_nopriv_{$action}
action has not been hooked with an {$action}
that matches the action
data parameter sent with your request. So either your callback is not hooked, or you're not sending the action correctly. Your code is making both errors.
- You are encoding the data sent to the server as JSON. WordPress looks for
$_REQUEST['action']
to trigger the appropriate action. When data is sent to the server as JSON,$_REQUEST
cannot be populated, so$_REQUEST['action']
does not exist, meaning that your callback is never run. You need to removeJSON.stringify()
from your code. - You are running
add_action()
forwp_ajax_myblog_ajax_request
inside a page template. This won't work. You are sending your request towp-admin/admin-ajax.php
, but that code does not load templates, so your callback is not hooked for that request. You need to useadd_action()
inside a file that is loaded insidewp-admin/admin-ajax.php
, such as your theme's functions.php file, or a plugin.
Here is your problem:
blogcontent.php
When WP is contacted to handle the Admin AJAX request, it doesn't load a page template. Remember, every request to WP loads WP from a blank slate. It doesn't know anything about the previous requests, only what it's told.
So because you aren't requesting that page, the template never loads, the filters never run, so there is no AJAX handler to take your request.
So instead, move your filters to functions.php
. Also consider using the modern REST API to handle your requests, it's easier, nicer to debug with human readable error messages, and it'll sanitize authenticate and validate for you if you tell it how! You even get a nice friendly URL.
Once that's been done, undo all the other things you did to try and fix this, like setting the datatype, or contenttype, that's hurting you not helping.
Send is as object, not a JSON string
Remove content type, you should let is default (
application/x-www-form-urlencoded
)Remove dataType - you send response as text, not a json. ( for JSON response use
wp_send_json
)Ensure that you register you ajax actions in init files ( your plugin main file or functions.php )
Also you can try debug it step by step in wp-admin/admin-ajax.php. 400 error means you code get this file, but action isnt recognized
url: myblog_ajax_obj.ajaxurl, data: { action: 'myblog_ajax_request', fruit: fruit, nonce: myblog_ajax_obj.nonce }, success: function(data) { console.log(data); }
JSON.stringify
. This won’t work because$_POST['action']
won’t be populated. See the example from the documentation: developer.wordpress/plugins/javascript/ajax/… – Jacob Peattie Commented Jul 21, 2020 at 12:240
, has pretty URLs, it'll even handle authentication checking for you with a few extra parameters – Tom J Nowell ♦ Commented Jul 21, 2020 at 13:22