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 with add_action('wp_ajax_(action)',
...)
or add_action('wp_ajax_nopriv_(action)', ...)
, then
admin-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.
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.