简体   繁体   中英

How do I get the correct php array format for WordPress Ajax $_POST data?

I'm implementing ajax within WordPress for the first time but running into a block here and I can't figure out the issue. Any help is appreciated.

So I'm basically trying to pass data to an ajax callback within WordPress.

JS:

    window.utils.http({
      method: 'POST',
      url: ajaxurl + '?action=ajax_submit',
      json: true,
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        test: 'testing123',
        quiz_results: {
          'a': 1,
          'b': 4,
          'c': 2
        }
      },
      onload: (response) => {
        console.log(response);
      },
    })

Note: I get the same issue even with jQuery's ajax function

Functions.php:

    function ajax_submit() {
        print_r($_POST);

        wp_die();
    }

    add_action('wp_ajax_ajax_submit', 'ajax_submit');
    add_action('wp_ajax_nopriv_ajax_submit', 'ajax_submit');

My JS console log response:

Array
(
    [{"test":"testing123","quiz_results":{"a":0,"b":0,"c":0}}] => 
)

As you can see, the php array isn't formatted correctly, I'm unable to select values too. If I echo $_POST['test'] or echo $_POST[0]->['test'] I get nothing.

Thanks

Try wp_send_json()

function ajax_submit() {
    print_r($_POST);
    wp_send_json( $_POST );
    wp_die();
}

add_action('wp_ajax_ajax_submit', 'ajax_submit');
add_action('wp_ajax_nopriv_ajax_submit', 'ajax_submit');

Sometime you can't access data through the superglobal $_POST . In your case modify your ajax_submit function like this

function ajax_submit() {
    // reading raw data from request body
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    wp_send_json( $data, 200);
    wp_die();
}

for more info see this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM