• I am developing a plugin, and on an admin page I have a table listing the entries from a custom mysql table. I added a checkbox for each row containing the id to enable the deletion of the rows checked.
    I have problems in sending data to the endpoint, as it is not found (404 error). I used the fetch method for the first time (in another front-end page of the plugin I use endpoints but not with fetch and they work fine), as I found it here https://stackoverflow.com/questions/46204166/wordpress-rest-api-authentication-using-fetch

    Here the function for the axax call on the admin page

    <script>
        //check all checkboxes
    (function( $ ) {
        // Function to handle AJAX requests for deleting and exporting entries
       function handleAjax(action, data) {
            // Construct the URL for the REST API endpoint
            var customEndpointUrl = '/wp-json/sight-form-tethys/v1/' + action;
           // Make the AJAX request using fetch
            fetch(customEndpointUrl, {
                method: 'POST',            
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': '<?php echo wp_create_nonce('wp_rest'); ?>'
                },
                credentials: "same-origin",
                body: JSON.stringify({ data: data })
            })
            .then(response => {
                if (response.ok) {
                    // Handle success response
                    console.log('Entries ' + action + ' successfully');
                } else {
                    // Handle error response
                    console.error('Error ' + action + ' entries');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
       $('#delete_selected').on('click', function() {
            var selectedEntries = [];
            
            $('input[type="checkbox"]:checked').each(function() {
                var entryId = $(this).attr('name');   
                selectedEntries.push(entryId);      
            });
            console.log(selectedEntries);
            
            handleAjax('delete_entries_ajax', selectedEntries);
        });
    })( jQuery );
    </script>

    and this is the registered endpoint

    	public function __construct( $plugin_name, $version ) {
    
    		$this->plugin_name = $plugin_name;
    		$this->version = $version;
    		add_action('admin_menu', array( $this, 'addPluginAdminMenu' ), 9);
    		add_action('admin_init', array( $this, 'registerAndBuildFields' ));	
    		add_action('admin_notices', array( $this,'sigh_form_tethys_admin_notice'));
    		add_action('rest_api_init', array( $this, 'register_delete_entries_endpoint'));
    
    	}
    	public function register_delete_entries_endpoint() {
    			$namespace = 'sight-form-tethys/v1';
    			$route = 'delete_entries_ajax';
    			register_rest_route($namespace, $route, array(
    				'methods' => 'POST',
    				'callback' => [$this,'delete_entries_rest_api_callback'],
    				'permission_callback' => [$this, 'delete_entries_rest_api_permissions_check'],
    			));
    		}
    		
    		public function delete_entries_rest_api_permissions_check($request) {
    			// Perform permission check logic here
    			return current_user_can('manage_options');
    		}
    		public function delete_entries_rest_api_callback($request) {
    			
    			$selectedEntries = $request->get_param('data');
    			file_put_contents('somefilename.txt', print_r($selectedEntries, true), FILE_APPEND);
    			// Perform delete operation for selected entries
    			// Example: $wpdb->delete($table_name, ['id' => $selectedEntries]);
    		
    			return new WP_REST_Response(array('message' => 'Entries deleted successfully'), 200);
    		}

    I noticed that after few seconds the error 404 is reported inspecting the Network, I see a series of ajax.php POST containing the id sent (the first, if more than one row is selected) with the following request, like if not finding the endpoint he call is sent to ajax.php

    Interval	"60"
    _nonce	"b50b096d6e"
    action	"heartbeat"
    screen_id	"sighting-form-tethys_page_sighting-form-tethys-entries"
    has_focus	"false"

    I already console.log all variables in the ajax call and they are correct. I also checked in wp-json that the endpoint created is registered.

    What is the problem? Thnaks a lot

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator bcworkz

    (@bcworkz)

    It’s not clear what the value is for action where you build the API’s URL or that it properly matches the route/endpoint you’ve registered.

    Where you register the route, $route does not have a leading /, so it’s likely your registered route does not match the URL you’re trying to fetch. Refer to the examples in the API Handbook for how to register custom routes.

    Thread Starter elena18

    (@elena18)

    action is given by the function

        $('#delete_selected').on('click', function() {
            var selectedEntries = [];
            
            $('input[type="checkbox"]:checked').each(function() {
                var entryId = $(this).attr('name');   
                selectedEntries.push(entryId);      
            });
            console.log(selectedEntries);
            
            handleAjax('delete_entries_ajax', selectedEntries);
        });

    so action = delete_entries_ajax

    If I console.log

    var customEndpointUrl = '/wp-json/sight-form-tethys/v1/' + action;

    I have

    /wp-json/sight-form-tethys/v1/delete_entries_ajax

    I am not sure what you mean about adding a leading / in $route. I checked the address https://localhost/mysite/wp-json and the route is registered correctly

    Moderator bcworkz

    (@bcworkz)

    It’s not that easy to spot minor syntax errors in /wp-json/ output. Compare the sample code from the handbook:
    register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array( //...
    with what yours would resolve to:
    register_rest_route('sight-form-tethys/v1', 'delete_entries_ajax', array( //...
    The regex (?P<id>\d+) may not apply in your situation, but the lack of a leading slash in your second parameter is significant. Your registered route/endpoint is thus:
    /wp-json/sight-form-tethys/v1delete_entries_ajax
    and not what you requested.

    Thread Starter elena18

    (@elena18)

    Thanks very much. I see the point. I added the leading slash to my $route as follows

    public function register_delete_entries_endpoint() {
    			$namespace = 'sight-form-tethys/v1';
    			$route = '/delete_entries_ajax';
    			register_rest_route($namespace, $route, array(
    				'methods' => 'POST',
    				'callback' =>[$this,'delete_entries_rest_api_callback'],
    				'permission_callback' => [$this, 'delete_entries_rest_api_permissions_check'],
    			));
    		}

    However the problem is not solved. I checked in many other forums and the whole code seems correct. I have no ideas why this is happening

    Moderator bcworkz

    (@bcworkz)

    I’m not really familiar with the Fetch API. I’m curious, if you are using jQuery anyway, why not use jQuery methods such as .ajax() or .post()? Even if you’re keen to use fetch() anyway, it would help narrow down where the problem lies if you used better documented jQuery methods. If jQuery can successfully get a response from your endpoint, then you know the issue lies in how you use fetch() and not how you registered your endpoint. If that’s the case, you can focus on properly implementing fetch() and be assured the WP API end of things is OK.

    Thread Starter elena18

    (@elena18)

    Yes you probably are right. I found in some forums/tutorials the fetch api and wanted to try it, but it seems really not working very well. I am sure there’s something I am missing in my whole code that gives the error, as I am totally new to develop a plugin structure. In the front end of the plugin I am using a normal ajax and it works fine. So I guess I will take your advise!!

    Thanks a lot

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Endpoint not found, but correctly registered’ is closed to new replies.