Inside a subdirectory of my plugin I have a file called insertproducts.php and I need to call that through an Ajax request. I have something like this:

            url:  "insertproducts.php",
        }).done(function(data) {

But the script cannot find the file and tries to look for:


Looking around to find out the problem and I read that WP points all the ajax requests to admin-ajax.php.

How do I run my custom url now?

1 Answer 1


Read more about AJAX in Plugins.

How to use Ajax in WP: 1. Register file contain functions, event of javascript or jquery. All data will be submit by events js

add_action( 'wp_enqueue_scripts', 'ajax_scripts' );
function ajax_scripts() {
    wp_register_script( 'main-ajax', get_template_directory_uri() . '/assets/js/main-ajax.js', array(), '', true );
    $arr = array(
        'ajaxurl' => admin_url('admin-ajax.php')
    wp_localize_script('main-ajax','obj',$arr );

inside main-ajax.js (data will be process through by admin-ajax.php) :

    url:  obj.ajaxurl,
}).done(function(data) {

2. File PHP to process functions (insertproducts.php) after submit data by ajax. Use below action for your function.

add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
  • Thanks Mr. Optical. About the last part, Do you mean that I move all the scripts from my insertproducts.php into my_action function? Also why my_action call back has been called twice? Once for wp_ajax_my_action and once for wp_ajax_nopriv_my_action hooks? Wouldn't that cause problem?
    – agahi
    Jul 6, 2018 at 8:00
  • Unfortunately this doesn't solve the problem. The script still looks for admin-ajax.php inside wp-admin. Event if I change 'ajaxurl' => admin_url('admin-ajax.php') to 'ajaxurl'=>'insertproducts.php' it still looks for /wp-admin/insertproducts.php, strange!
    – agahi
    Jul 6, 2018 at 10:09
  • OK, thanks Mr. Optical. I change the line to 'ajaxurl' => plugin_dir_url( DIR ) .'insertproducts.php'
    – agahi
    Jul 6, 2018 at 10:20
  • "The script still looks for admin-ajax.php inside wp-admin" That is because admin-ajax.php is in /wp-admin.
    – Hans
    Sep 22, 2018 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.