0

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);
    });
  • Why does your URL have 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? – Tom J Nowell Dec 12 '19 at 19:25
  • Yes, as per the first sentence of my question when visited via browser this works perfectly well. What I really need to know why I am unable to access it with jQuery AJAX while it can be visited via browser with no issues. That's all. Thanks Tom – xyz83242 Dec 12 '19 at 20:19
0

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

| improve this answer | |
  • Hi Tom, thank you so much for your help! You are absolutely right. Instead of echo this needs to be return. You are absolutely right with the other point that json before being put into the database should be json_encoded, not json_decoded. It's easier to retrieve it later on. The last piece of the puzzle here is the jQuery.get a request that does not work my end. I have tried the request for the posts as you suggested did work for you. No luck. Copy-pasting that into the browser will however work and retrieve the default WP post. – xyz83242 Dec 12 '19 at 20:50
  • So you're unable to use a standard jQuery get on a Core WP posts endpoint? If it doesn't work, what happens instead? – Tom J Nowell Dec 12 '19 at 20:51
  • The funny thing is I am using jQuery all over the place. I have added .fail to the ajax request with console log. So it's definately going through. What I am getting in response message is actually response with all the posts (I am trying your post path) but in front of it is again the funny text: "Getting time from the server, no need to check, use the saved JSON list in the db1523<br>[{"id":1,"date":"2019-12-07T07:32:49","date_gmt":"2019-12-07T07:32:49","guid": etc ... – xyz83242 Dec 12 '19 at 21:10
  • OK, solved it. Turned on WP_DEBUG and cleared the error in the code. I had one error with Array to string conversion in one of the include files. That was causing the weird error in the REST api and as result my jQuery query calling the endpoint. Thanks for your help! – xyz83242 Dec 12 '19 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.