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
2
Answers
Try
wp_send_json()
Sometime you can’t access data through the superglobal
$_POST
.In your case modify your
ajax_submit
function like thisfor more info see this answer