0

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

rhysmatthew
  • 13
  • 1
  • 4

2 Answers2

0

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');
Bhautik
  • 11,125
  • 3
  • 16
  • 38
  • thanks but not sure that works here it gives me : {"{\"test\":\"testing123\",\"quiz_results\":{\"a\":0,\"b\":0,\"c\":0}}":""} I need the data on the php side, not the JS side (that's mainly for testing the response) – rhysmatthew Jun 10 '21 at 11:38
  • can you tell us what is the output of this print_r($_POST); – Bhautik Jun 10 '21 at 11:38
  • It's just strange to me that echo $_POST['test'] doesn't work here, when everywhere online says it should. – rhysmatthew Jun 10 '21 at 11:39
  • Output for print_r($_POST) is : Array ( [{"test":"testing123","quiz_results":{"a":0,"b":0,"c":0}}] => ) – rhysmatthew Jun 10 '21 at 11:40
  • try to print echo ` "
    "; print_r($_POST); echo "
    ";` and post output this in your question.
    – Bhautik Jun 10 '21 at 11:40
  • Array ( [{"test":"testing123","quiz_results":{"a":0,"b":0,"c":0}}] => ) – rhysmatthew Jun 10 '21 at 11:43
0

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

Joy Kumar Bera
  • 314
  • 2
  • 8