1

I am trying to separate a part of my code from the functions.php file to make it easier to understand and maintain. So I want to put all my "ajax" related code in a different PHP file.

Here is the require in my functions.php file:

require_once( __DIR__ . '/includes/ajax.php');

And here is some of the content of the ajax.php file:

function theme_enqueue_ajax(){
    wp_localize_script( 'myJSScript', 'ajaxUrl', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( "wp_enqueue_scripts", "theme_enqueue_ajax");

If I put the code from ajax.php directly in my functions.php file, everything works fine, but once I move it to ajax.php the ajaxUrl variable doesnt exist anymnore.

0

1 Answer 1

0

Of course there can be many reasons, but if you require ajax.php in functions.php above the hook with wp_enqueue_script( 'myJSScript' ...); - it will not work.

wp_localize_script()
Works only if the script has already been added.

function theme_enqueue_ajax(){
    //try to add wp_enqueue_script( 'myJSScript' ...); here
    wp_localize_script( 'myJSScript', 'ajaxUrl', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( "wp_enqueue_scripts", "theme_enqueue_ajax");
1
  • Well, that was it! I feel somewhat dumb for not noticing it myself, but thanks! Commented May 13, 2021 at 11:47

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.