In my plugin, I have some jQuery-Ajax code that processes form data and adds it to the database as soon as the button is clicked. Since many people have a different path to their plugin folder, I was wondering if there was anyway to standardize the URL that points to the data processing PHP file. See my example below:
$.ajax({
type: "POST",
url: "url_to_php_file_path.php",
data: data,
cache: false,
success: function() {
alert.("added");
}
});
Firstly, all ajax calls should be registered through
wp_ajax
This code should be in your plugin file, along with the function
add_something
Then in the front end, you should be using the
ajaxurl
global variable supplied by Wordpress.This negates the need to explicitly declare any URL, and as such, is the proper way to perform ajax calls in Wordpress.
Figuring out the target URL
In WordPress, all AJAX requests must be made to the following URL:
You should not make an AJAX request directly to a file residing in the plugin or theme directory.
Also, do not hard-code the above URL, instead you should use the following function to construct the URL:
Alternatively to the above, you can use
wp_localize_script()
, but this is not required, the above is fine too.Note: Don't worry about the "admin" part, this URL is the correct one to use for all users, including non-logged-in (guest) users.
Tell WordPress what function to use for your AJAX request
You need to let WordPress know which function should process your AJAX request.
For that purpose you'll create a custom function, and register it using the
wp_ajax_*
andwp_ajax_nopriv_*
hooks:Don't forget to specify "mycustomfunc" in the AJAX request too
Finally, here is how you would make a proper AJAX request:
Combine it all
If you had to put it all into one file, here's how you'd do it:
Note: For the
ajax_url
part, you could usewp_localize_script()
instead of setting it manually, but it is less flexible as it requires to specify an existing enqueued script, which you might not have.Note: Also, for outputting inline JavaScript manually into a page, the
wp_footer
hook is the correct one to use. If usingwp_localize_script()
then you would use thewp_enqueue_scripts
hook instead.