I am trying to access to a custom php file in WP theme directory to pass to an jQuery Ajax call. I have added foloowing 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)

can you please let me know what I am missing?


And it had no chance to work correctly.

When you use wp_localize_script like that:

wp_localize_script( $handle, $name, $data );

then the object called name is defined and data is it's content. As you can see in this example from Codex.

So you can't use ajaxurl in your JS file, because there is no such variable defined anywhere in your code.

The correct way is:

var request = $.ajax({
type: "POST",
url: ajax_custom.ajaxurl,
  • Thanks alots Krzysiek, this is working now but I have another problem! how come the URl is landing in wp-admin folder like http://localhost/WP/wp-admin/session.php instead of the theme directory?
    – Behseini
    Jun 15 '18 at 6:27
  • @Behseini because that’s what admin_url function is for... And you should send it to admin-ajax.php and no to session.php Jun 15 '18 at 6:31
  • @Behseini I think you should read this article before trying to code anything more: codex.wordpress.org/AJAX_in_Plugins Jun 15 '18 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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