2

I try to load a post with Ajax.

functions.php:

function my_action_callback() {
        wp_localize_script('jscustom', 'ajax_custom', array(
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
        wp_enqueue_script('jscustom');
}
add_action('wp_ajax_my_action', 'my_action_callback');

jQuery code in custom.js:

jQuery(window).load(function() {
    var morebutton = jQuery('#load-more'),
        archive = morebutton.rel,
        deftext = morebutton.text(),
        page = 1;

    morebutton.click(function(e){
        e.preventDefault();
        page++; 

    morebutton.text(ajax_custom.loading);
    jQuery.post(ajax_custom.ajaxurl, {action:'load_more', page:page, archive:archive}, function(data){...

When I press the "load more" button, I get an error:

ReferenceError: ajax_custom is not defined

What is wrong?

8

wp_localize_script should be called AFTER wp_enqueue_script:

IMPORTANT!: wp_localize_script() MUST be called after the script it's being attached to has been enqueued or registered. It doesn't put the localized script in a queue for later scripts.

Fix it in your function:

function my_action_callback() {
wp_enqueue_script('jscustom'); // I assume you registered it somewhere else
wp_localize_script('jscustom', 'ajax_custom', array(
   'ajaxurl' => admin_url('admin-ajax.php')
));

}

You can always check in your page's <head> if you see your variable.

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.