I have REST endpoint in WordPress and I am trying to ping it with jQuery from the fronted script. This works when questioned via browser: http://example.com/wp-json/wpc_ylp/v2/videos/
But it does not work when I am trying to reach it from the frontend with jQuery. I have tried different AJAX requests but I am unable to get any response. Does anyone know what am I doing wrong?
Rest endpoint here:
// REST END POINT FOR THE VIDEOS
function wpc_ylp_rest_videos( ) {
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wpc_ylp/v2', '/videos', array(
'methods' => 'GET',
'callback' => 'wpc_ylp_rest_videos',
) );
} );
jQuery AJAX trying to reach the endpoint:
jQuery.get( target = '/wp-json/wpc_ylp/v2/videos/', function( data ) {
console.log( 'DATA',data )
});
or
jQuery.ajax({
url: '/wp-json/wpc_ylp/v2/videos'
}).done(function( data ) {
console.log('dataxxx',data);
});
target =
before it? Have you confirmed your endpoint is there by visiting it in your browser? It's extremely unusual that your endpoint encodes and outputs its own content, is there a reason you don't return the data from the function like the docs? Also where is the code that creates$myObj
? Is there more to your endpoint that's been removed to fit in this question?