Wordpress admin-ajax.php 400 bad request
Asked Answered
A

9

28

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.

(function( $ ) {
    var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
    $.ajax({
        url : ajaxscript.ajax_url,
        data : {
            action : 'cart_clb',
            id : 1
        },
        method : 'POST',
        success : function( response ){ console.log(response) },
        error : function(error){ console.log(error) }
    })
})(jQuery)

And inside my functions.php

add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );

function cart_clb(){
    echo json_encode($_POST);
    die();
}

As said above when i execute the request :

mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Someone could help me to please? thank you.

Asymptote answered 29/12, 2017 at 16:56 Comment(0)
W
41

First, use full and absolute url, with protocol (or at least protocol-independent form):

var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' } 

Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:

data : {
    action : 'post_cart_clb',
    id : 1
},
When answered 29/12, 2017 at 17:45 Comment(2)
I think this should mark as correct answer as it highlighted issue and fix.Bandwidth
This is the only approach that worked for me. Thank you!Etymon
U
16

wp_ajax_nopriv_(action) executes for users that are not logged in. So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:

add_action( 'wp_ajax_my_action', 'my_action' ); // for loggin users

add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for non loggin users

Unbound answered 24/6, 2021 at 17:55 Comment(1)
Ahhhhhhhh! Thank you Rajan, this was very helpful for me!Astor
P
12

I have modified your code and look at this :

(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
    url : ajaxscript.ajax_url,
    data : {
        action : 'post_cart_clb',
        id : 1
    },
    method : 'POST', //Post method
    success : function( response ){ console.log(response) },
    error : function(error){ console.log(error) }
  })
})(jQuery)

This is the syntax of WordPress ajax : wp_ajax_{Your_action_name} wp_ajax_nopriv_{Your_action_name}

Pursuivant answered 29/12, 2017 at 18:3 Comment(2)
Hello, thanks for your all response, the issue is this : wp_ajax_post_cart_clb the "post" is not valid, i had to write wp_ajax_cart_clb where the cart_clb is the action used from ajax query.Asymptote
great, great. thanks for your help. I was stuck here for two hoursWrongly
F
11

admin-ajax.php returns Bad Request headers in 2 situations, when the action function is not registered, and when the action parameter is empty.

I had same error and the issue was that i forgot to add_action('wp_ajax_nopriv'...) i had only wp_ajax_nopriv set, so when i was logged in as admin nesting, it was not working.

Fabron answered 22/5, 2022 at 17:56 Comment(0)
P
6

In my case, I am using Class based approach. And I found the issue was because I was using wp_ajax_ request in constructor.

If you are using ajax methods inside class, move wp_ajax_ handles outside of class (write in main plugin file) and pass classname and method name. For example:

add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );
add_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] ); 
Paunchy answered 18/11, 2020 at 7:54 Comment(1)
Thanks heap Deepak bhai sahib. This was indeed my use case as wellTenuis
C
4

Just Use

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

For more detail, check the below link
https://codex.wordpress.org/AJAX_in_Plugins

Coumarone answered 1/7, 2021 at 15:35 Comment(0)
K
2

In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:

request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');

So please be sure that jQuery appends as well that header.

Kristopherkristos answered 4/3, 2020 at 21:10 Comment(0)
R
1
  1. in the url use /wp-admin/admin-ajax.php and try to have a local domain because with localhost or localhost/wordpress this might be weird, on the server this will work fine

  2. try to use fetch or XMLHttpRequest to have more control over the request and don't send data as json send it in a formData object const formData = new FormData();

     fetch(loader.ajax_url, {
         method: "POST",
         body: formData,
     }).then((resp) => {
             console.log(resp);
     }).catch((resp) => {
             console.log(resp);
     });
    

it is possible to have it work with other combinations but i find this almost perfect

Reporter answered 3/3, 2021 at 20:32 Comment(0)
H
0

If you prefer using Javascript Fetch API over Jquery ajax, ensure the following:

  • You are using the correct Content-Type
  • Your data is well formatted
  • Your response is extracted properly

You are using the correct Content-Type

  • By default, the fetch uses text/plain, change this to

    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    }

Your data is well formatted

  • By changing the content type, we also have to change the type of data we are sending over to the server i.e.
 action=action_name&id=1

Your response is extracted properly

  • The fetch is a little weird with its responses i.e.
 const response = await fetch(ajax_params.ajax_url);

will return a promise, not a value, therefore we need an extra step

  const htmlText = await response.text();
  console.log(htmlText) // this is a value

Putting it all together

  const response = await fetch(ajax_params.ajax_url, {
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: 'action=action_name&id=1'
  });

  const html = await response.text();

  document.getElementById("data-container").innerHTML = html;

Hayfork answered 15/5, 2024 at 14:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.