400 error when send JSON data to WordPress Admin Ajax with Fetch API

Viewed 355

I use Fetch Api with WordPress admin-ajax.php.

  1. Send data as URLSearchParams. It's WORKING.
    let data = {
        action: 'my_action',
    }
    
    fetch( ajaxurl, {
        method: 'POST',
        credentials: 'same-origin',
        body: new URLSearchParams(data)
    });
  1. Send data as FormData. It's WORKING.
    let data = New FormData();
    data.append('action', 'my-action');
    
    fetch( ajaxurl, {
        method: 'POST',
        credentials: 'same-origin',
        body: data
    });
  1. Send data as JSON . It's NOT WORKING, 400 ERROR.
    let data = {
        action: 'my_action',
    }
    
    fetch( ajaxurl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });

I'm curious why it got 400 error? anything I miss?

1 Answers

change your fetch login as below and try. Since you are specifying 'Content-Type' : 'json' , no need to stringify the json.

    fetch( ajaxurl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json'
        },
        body: data
    });
Related