AJAX action through direct link

I have an existing AJAX action that's already defined by the theme I'm using. The action deletes a search item request, and I'd like to use it as a direct link - like an Unsubscribe link - emailed to the user along with the search results...

Something like the following URL: https://domain.tld/wp-admin/admin-ajax.php?action=delete_saved_search_item=search_item_id=17 but I get a 0 on the screen and a 400 Bad Request in the Headers.

Basically in the JS it's defined like this:

            $.post(ajaxurl,
                {
                    action: 'delete_saved_search_item',
                    search_item_id: search_item_id,
                },
                function (response) {
                    response = JSON.parse(response);
                    if (response.success) {
                        search_item.remove();
                    }
                }
            );

so I suppose it expects a POST request, not a GET one... Is there any workaround to make this work? Like creating a page with a custom cURL that would imitate the POST form submission? Anyone done something like this? The good thing is I didn't notice any use of nonce, so I suppose this alone makes it easier to handle, doesn't it?

Topic ajax Wordpress

Category Web


Use WordPress' generic POST/GET handler wp-admin/admin-post.php

Don't let the name confuse you - it accepts both GET/POST, and just like admin-ajax.php it accepts both authorised (admin) and non-authorised (public) requests.

function wpse_406199_custom_action() {
    // Do something!

    // Maybe redirect back to where they came from?
    wp_redirect( wp_get_referer() );
    exit;
}

// Non-logged-in requests
add_action( 'admin_post_nopriv_wpse_406199_custom_action', 'wpse_406199_custom_action' );

// Logged-in requests
add_action( 'admin_post_wpse_406199_custom_action', 'wpse_406199_custom_action' );

And to get the URL:

$action_url = admin_url( 'admin-post.php?action=wpse_406199_custom_action' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.