Why am I getting a Status Code: 400 Bad Request error with WP Ajax?

时间秒杀一切 提交于 2021-01-07 02:48:15

问题


I have been troubleshooting this for hours now and I am stumped as to why this error is occurring.

in my JS I have the following ajax:

var $ = jQuery; // define jquery
let name = "Mark";
let pies = "cherry";

$(document).ready(function(){
    $.ajax({
        type : 'POST',
        dataType : 'json',
        url : ajaxurl,
        nonce: nonce,
        data : {
            action: 'myfunction',
            name: name,
            pies: pies,
            nonce: nonce
        }
    }).done(function(response) {
        console.log(response);
    });
}); // end document ready

and in my plugin's PHP, I have

    function myfunction() {    
        if ( wp_verify_nonce( $_POST['nonce'], 'registration_nonce')) {
            $name = $_POST['name'];
            $pies = $_POST['pies'];
            file_put_contents('debug_output.txt', $pies);
            die();
        }
    }
    add_action( 'wp_ajax_myfunction', 'myfunction' );
    add_action( 'wp_ajax_nopriv_myfunction', 'myfunction');

This gives me a 400 every single time. This should be a simple thing and I normally do this all of the time but for some reason, I am seriously missing something. Any ideas anyone? I whittled it done to the bare minimum and still no luck. Both the ajax URL and nonce are fine. Did something in WP change?


回答1:


There are some things that maybe you should fix/check:

  1. in your PHP action end with something like echo json_encode($myDataArray) where $myDataArray is something like array("key" => "value") ecc..
  2. Your last function call inside the PHP action should always be "die" or "exit" or just use the WP wp_send_json(); (you have alternatives for success/errors)
  3. Double check that ajaxurl actually points to admin_url( 'admin-ajax.php' )
  4. Double check that your add_action hooks get called somewhere in your page before the AJAX call actually occours



回答2:


Typo?

add_action( 'wp_ajax_nopriv_myactiont', 'myaction');

// should be

add_action( 'wp_ajax_nopriv_myaction', 'myaction');

// final result

function myaction(){
  echo "success";
  exit;
}
add_action( 'wp_ajax_myaction', 'myaction' );
add_action( 'wp_ajax_nopriv_myaction', 'myaction');

Diego's answer has some good points to check too.



来源:https://stackoverflow.com/questions/64933027/why-am-i-getting-a-status-code-400-bad-request-error-with-wp-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!