Wordpress returns 400 Bad Request on ajax call with fetch API

Viewed 1878

I am making a Ajax call to the admin-ajax.php with a fetch API syntax. Here is the code that calls the back-end script:

fetch(ajax_obj.ajaxurl, {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    body: JSON.stringify(this.data),
    headers: {
      "Content-Type": "application/json"
    }
  })

and getting 400 Bad Request response.

Can someone tell me where does this request is not right?

When checking the Network Development Tools in chrome, I can see that the body that is sent is ok, the url is also ok... ... and as far as I know 4xx status codes are for errors on the client, so I don't even look on the server side code... if I am wrong please give me feedback on this...

Actually, I had jQuery ajax call like this:

this.data = {
              'action': 'ajax_product_query',
              'locations': this.locations,
              'type': this.category != '' ? this.category : [],
              'all-locations': this.filters['locationFilter'].all.checked,
              'page': ajax_obj.current_page
            };

          $.ajax({
            url: ajax_obj.ajaxurl,
            method: 'post',
            dataType: 'json',
            data: this.data,
            beforeSend: function(xhr) {
              button.innerHTML = 'Loading...';
            },
            success: (data) => {  ...

... and it worked like a charm...

Than, willing to remove jQuery dependency, wanted to turn the jQuery ajax call into Fetch API syntax like this:

fetch(ajax_obj.ajaxurl, {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    body: JSON.stringify(this.data),
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => response.json()) ...

And than the requests turned into 400 Bad Requests...

Thanks!

1 Answers

Because after JS fetch 'POST' request you can't get $_POST data in Php. Dirty solution. You could add this code in u "/wp-admin/admin-ajax.php" to resolve this:

if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
  $post = trim(file_get_contents("php://input"));
  $_POST = ( array ) json_decode( $post );
    $_REQUEST['action'] = $_POST['action'];
}

Or try to find a better solution.
P.S. Sorry for my English

Related