simlpymarkb
simlpymarkb

Reputation: 385

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

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?

Upvotes: 0

Views: 409

Answers (2)

mikerojas
mikerojas

Reputation: 2338

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.

Upvotes: 0

Diego
Diego

Reputation: 1716

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

Upvotes: 1

Related Questions