Search code examples
javascriptajaxwordpresswordpress-rest-api

How to set ajax for register_rest_route function and WP_REST_Controller class?


I could not find a good source that answers my question directly.

How can we define our Ajax which can navigate through the different update, add, and delete functions in WP_REST_Controller?

I am a little confused do I need to add a new function that redirects requests? Or do I need to set a different route? or can I tell what callback function I want from that route by javascript?

For example, I have two fetch functions for deleting and updating on the same route. How do we say which callback function on the backend we want to execute?

let delete_contact = () => {
fetch('http://localhost/wreact/wp-json/redapple/v1/contactsinfo',{
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'accept': 'applicaiton/josn',
        'Authorization': `Bearer ${localStorage.getItem('jwt')}`
    },
    body:JSON.stringify({
        action: 'delete_item',
        // nonce: nonce,
        id: 21
    }).then(function(response){
   return response.json()
}).then(function(post){
document.body.getElementsByClassName('present')[0].textContent = 
JSON.stringify(post);
});
}

let add_contactsInfo = () => {

  fetch('http://localhost/wreact/wp-json/redapple/v1/contactsinfo', {
      method: "POST", 
      headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('jwt')}`
      },
      body:JSON.stringify({
          title: 'Title',
          content: 'Content',
          status: 'publish'
      })

     }).then(function(response){
       return response.json()
    }).then(function(post){
    document.body.getElementsByClassName('present')[0].textContent = 
    JSON.stringify(post);
    });
}

And this is the route class

<?php

class Slug_Custom_Route extends WP_REST_Controller
{

    public function register_routes()
    {
        $version = '1';
        $namespace = 'redapple/v' . $version;
        $base = 'contactsinfo';
        register_rest_route($namespace, '/' . $base, array(
          array(
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => array( $this, 'get_items' ),
            // 'permission_callback' => array( $this, 'get_items_permissions_check' ),
            'args'                => array(

            ),
          ),
          array(
            'methods'             => WP_REST_Server::CREATABLE,
            'callback'            => array( $this, 'create_item' ),
            // 'permission_callback' => array( $this, 'create_item_permissions_check' ),
            'args'                => $this->get_endpoint_args_for_item_schema(true),
          ),
        ));
        register_rest_route($namespace, '/' . $base , array(
          array(
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => array( $this, 'get_item' ),
            'permission_callback' => array( $this, 'get_item_permissions_check' ),
            'args'                => array(
              'context' => array(
                'default' => 'view',
              ),
            ),
          ),
          array(
            'methods'             => WP_REST_Server::EDITABLE,
            'callback'            => array( $this, 'update_item' ),
            'permission_callback' => array( $this, 'update_item_permissions_check' ),
            'args'                => $this->get_endpoint_args_for_item_schema(false),
          ),
          array(
            'methods'             => WP_REST_Server::DELETABLE,
            'callback'            => array( $this, 'delete_item' ),
            // 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
            'args'                => array(
              'force' => array(
                'default' => false,
              ),
            ),
          ),
        ));
        register_rest_route($namespace, '/' . $base . '/schema', array(
          'methods'  => WP_REST_Server::READABLE,
          'callback' => array( $this, 'get_public_item_schema' ),
        ));
    }


    public function create_item($request)
    {

        return new WP_REST_Response('Created', 200);
    }

    public function delete_item($request)
    {

       return new WP_REST_Response('deleted', 200);
    }

}


function register_contactsinfo_controller()
{
    $controller = new Slug_Custom_Route();
    $controller->register_routes();
}

add_action('rest_api_init', 'register_contactsinfo_controller');


Solution

  • The answer to my question is the method: 'DELETE'. Since we have set that for the route, and the route for deleting, updating, and getting only one item should be the same. we add the product id as part of the URL since we are working on one product only. All of them are applied based on the request method in ajax we can navigate => 'DELETE' for delete, 'POST' for the update, and 'GET' to get one post.

    for example: http://localhost/wreact/wp-json/redapple/v1/contactsinfo/21

    where 21 is the post id. This can be used for all three scenarios.

    What I was missing and did not know was the 'DELETE' option here:

    
    let delete_contact = () => {
        fetch('http://localhost/wreact/wp-json/redapple/v1/contactsinfo/21',{
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'accept': 'applicaiton/josn',
                'Authorization': `Bearer ${localStorage.getItem('jwt')}`
            },
            body:JSON.stringify({
                // nonce: nonce,
                id: 21
            })
        }
        ).then(function(response){
            console.log(response)
            document.body.getElementsByClassName('present')[0].textContent = JSON.stringify(response);
        });}