However, since WordPress already uses AJAX calls internally, it doesn’t make sense to write extra code to pass data and then write even more to coordinate everything WordPress can handle some of those tasks with its own wp_ajax (action) function that comes not only with the benefit of having WordPress make the calls for you from the server-end, but also allows you to register functions within existing action hooks.
Starting with the above code in a file named “test.js”, the script would first need to be enqueued before it could be used within a plugin. While doing that, we can also define the action as the trigger for the call.
With the named “example_function” above, the same ‘action’ set in the AJAX call will look for and handle the hooked function. AJAX calls with the ‘action’ set to “example_function” will be routed to the response from the function for that same action, too. Without needing to write or re-configure settings, WordPress will do all the handling using its own internal organizing and AJAX calls. However, while this shows how to use this within a plugin (and thus a user will be logged in to use it), there is also a version for unauthenticated users called wp_ajax_nopriv_(action) that works the same way for more front-end usage.