I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning data:0
. I've checked my response config and the ajax url is correct as well as "action". My functions.php
looks like this:
add_action("wp_ajax_sendhire", "sendhire");
add_action("wp_ajax_nopriv_sendhire", "sendhire");
function sendhire() {
$cars = array("Volvo", "BMW", "Toyota");
return json_encode($cars);
die();
}
The data, obviously, is just for testing.
I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning data:0
. I've checked my response config and the ajax url is correct as well as "action". My functions.php
looks like this:
add_action("wp_ajax_sendhire", "sendhire");
add_action("wp_ajax_nopriv_sendhire", "sendhire");
function sendhire() {
$cars = array("Volvo", "BMW", "Toyota");
return json_encode($cars);
die();
}
The data, obviously, is just for testing.
If you want to use Admin-Ajax to output the content, you should use echo
instead. There is nothing to be viewed when you use return
, so you'll get a 0
.
This quotation from the codex explains further about the 0
response:
If the Ajax request fails in
wp-admin/admin-ajax.php
, the response will be -1 or 0, depending on the reason for the failure. Additionally, if the request succeeds, but the Ajax action does not match a WordPress hook defined withadd_action('wp_ajax_(action)', ...)
oradd_action('wp_ajax_nopriv_(action)', ...)
, thenadmin-ajax.php
will respond 0.
Now, if you are going to output a JSON response, you should take a look into the REST API. Its default response type is JSON.
To do so, register a path for the endpoint, and create a callback function:
add_action( 'rest_api_init', function () {
register_rest_route( 'dcp3450', '/test_endpoint/', array(
'methods' => 'GET',
'callback' => 'sendhire'
) );
});
function sendhire() {
$cars = array("Volvo", "BMW", "Toyota");
return $cars;
}
Now by accessing http://example.com/wp-json/dcp3450/test_endpoint/
you will get your JSON response, and you can get rid of this annoying 0 that is following humanity to its end.
WordPress have a very useful API (REST API) for this work, you can use it, instead of sending ajax request. Here is the documentation have a look please https://developer.wordpress.org/rest-api/
echo
doesn't change the response. The will eventually process data being passed to it not return anything. Maybe a success/error message but that's about it. – dcp3450 Commented Jul 31, 2017 at 4:37