Search code examples
wordpresswordpress-theming

How to access Ajax enqeued file to pass to URL for Ajax call


I am trying to access to a custom php file in WP theme directory to pass to an jQuery Ajax call. I have added following code in function.php to register the script and PHP file:

function add_ajax() {
 wp_enqueue_script( 'addproducts', get_template_directory_uri() .'/js/addproducts.js', array('jquery'),'',true );
 wp_localize_script('addproducts', 'ajax_custom', array('ajaxurl' => admin_url('session.php')));
}
add_action( 'wp_enqueue_scripts', 'add_ajax' );

Now in my JavaScript file I am trying to pass URL like url: ajaxurl

var request = $.ajax({
type: "POST",
url: ajaxurl,

but I am getting the ajaxurl is not defined error:

addproducts.js?ver=4.9.6:6 Uncaught ReferenceError: ajaxurl is not defined at HTMLAnchorElement. (addproducts.js?ver=4.9.6:6) at HTMLAnchorElement.dispatch (jquery.min.js?ver=4.9.6:3) at HTMLAnchorElement.r.handle (jquery.min.js?ver=4.9.6:3)

What am I missing?


Solution

  • add this code in your functions.php

    var request = $.ajax({
    type: "POST",
    url: ajax_custom.ajaxurl,
    

    You need to call ajax_custom as it is the object of your ajax url

    There is another option is possible

    add_action('wp_head', 'myplugin_ajaxurl');

    function myplugin_ajaxurl() {
    
       echo '<script type="text/javascript">
               var ajaxurl = "' . admin_url('admin-ajax.php') . '";
             </script>';
    }
    add_action('init','myplugin_ajaxurl');