First, lets fix your endpoint:
function wpc_ylp_rest_videos( ) {
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
}
There are a few problems here:
- callbacks for REST API endpoints are meant to return their data, like shortcodes. The REST API does the JSON encoding, you’re not meant to
echo
$myObj
appears to have been summoned out of nowhere, this will generate a large amount of PHP notices and errors. Never do this, PHP will have to fill in the gaps, and relying on computer to “get what you meant” rarely works out- There’s actually a first parameter given to you that lets you read in parameters instead of using
$_GET
or$_POST
, that allows you to use a lot of the features
It would be much better like this:
function wpc_ylp_rest_videos( $request ) {
return [
'name' => 'John',
'age' => 30,
'city' => 'New York',
];
}
Second, I tested your AJAX request code with this:
jQuery.get( '/wp-json/wp/v2/posts/', function( data ) {
console.log( 'DATA',data )
});
The result worked as desired