WordPress Development Asked by JPL on November 6, 2021
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'
});
});
There'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.
$_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 remove JSON.stringify()
from your code.add_action()
for wp_ajax_myblog_ajax_request
inside a page template. This won't work. You are sending your request to wp-admin/admin-ajax.php
, but that code does not load templates, so your callback is not hooked for that request. You need to use add_action()
inside a file that is loaded inside wp-admin/admin-ajax.php
, such as your theme's functions.php file, or a plugin.Answered by Jacob Peattie on November 6, 2021
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.
Answered by Tom J Nowell on November 6, 2021
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);
}
Answered by Az Rieil on November 6, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP