I'm quite new to doing api calls using Wordpress so bear with me.
I have this function:
function foo() {
$userinfo = [
"number" => "26246426",
"secondnumber" => "43634643"
];
$api_url = 'https://api.url.com';
$response = wp_remote_post( $api_url, array(
// Set the Content-Type header.
'headers' => array(
'Content-Type' => 'application/json',
),
// Set the request payload/body.
'body' => json_encode( $userinfo ),
) );
$res_body = wp_remote_retrieve_body( $response );
echo $res_body;
die();
}
This works and I get a response.
Now what I'm trying to do is send the response in an action towards my ajax that's in a script right under the php function from above (everything is happening inside a plugin file)
Here are my actions
add_action('wp_ajax_add_foo', 'foo' );
add_action('wp_ajax_nopriv_add_foo', 'foo' );
And my ajax call inside a script tag under the function
var ajaxscript = { ajax_url : 'mywebsite.com/wp-admin/admin-ajax.php' }
jQuery(document).ready(function($) {
$.ajax ({
url: ajaxscript.ajax_url,
type: 'POST',
// dataType: 'application/json',
data: {
// the value of data.action is the part AFTER 'wp_ajax_' in
// the add_action ('wp_ajax_xxx', 'yyy') in the PHP above
action: '_add_foo'
// ANY other properties of data are passed to your_function()
// in the PHP global $_REQUEST (or $_POST in this case)
},
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
}) ;
});
I would be expecting to get back the $res_body variable but I'm getting a 400. Why is that?