$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>wp localize script - wp_localized_script is not defined when called via jquey ajax|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

wp localize script - wp_localized_script is not defined when called via jquey ajax

matteradmin11PV0评论

I am struggling to get my ajax request to work. It fails when I fire my $ajax and I get this error...

Uncaught ReferenceError: feature_ajax is not defined

This is my functions.php

// load our frontend modifiers
require_once(__DIR__ . '/lib/Frontend.lib.php');

This is my Frontend.lib.php class php...

class Frontend
{

    /** frontend constructor */
    public function __construct()
    {

        // enqueue our scripts
        add_action('wp_enqueue_scripts', array($this, 'action_wp_enqueue_scripts'));

        // add out ajax actions
        $this->ajax_actions();

    }

    /** frontend enqueued scripts */
    public function action_wp_enqueue_scripts()
    {

        // localize admin ajax
        wp_localize_script('ajax-actions', 'ajax_actions', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
        ));

        // enqueue scripts
        wp_enqueue_script('ajax-actions');

    }


    /** ajax actions */
    public function ajax_actions()
    {

        // admin field postdata ajax actions
        add_action('wp_ajax_field_postdata', [__CLASS__, 'field_postdata']);

        // public field postdata ajax actions
        add_action('wp_ajax_nopriv_field_postdata', [__CLASS__, 'field_postdata']);

    }

    // Field Post Data
    public static function field_postdata()
    {
        global $post;
        $post_id = ($_REQUEST['id']);

        if($post_id){
            $post = get_post($post_id);
            setup_postdata($post);
            get_template_part('ajax/modal','field');
            die();
        }

    }

}

new Frontend();

When I fire the $ajax script below, this is when I get the error feature_ajax is not defined.

But it is defined in the code above.

This script below is my theme-min.js file

// load feature post data
$.ajax({
    cache: false,
    timeout: 8000,
    url: ajax_actions.ajaxurl,
    type: 'POST',
    data: {
        action: 'field_postdata',
        id: post_id
    },
    success: function (data) {
        alert(data);
    }
});

Any help in understanding what i'm doing wrong would be great.

Thanks


Updated Fixed Code

So what I changed to make this work. I was already enqueuing my main-min.js file, so I combined my wp_localize_script using the same handle as my enqueued javascript and it worked.

// register js in footer
$filename = get_template_directory_uri() . '/assets/scripts/main-min.js';
wp_register_script('main-js', $filename, array(), rand(), true);

// localize theme-js ajax actions
wp_localize_script('main-js', 'ajax_actions', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' )
));

// enqueue required scripts
wp_enqueue_script('main-js')

I am struggling to get my ajax request to work. It fails when I fire my $ajax and I get this error...

Uncaught ReferenceError: feature_ajax is not defined

This is my functions.php

// load our frontend modifiers
require_once(__DIR__ . '/lib/Frontend.lib.php');

This is my Frontend.lib.php class php...

class Frontend
{

    /** frontend constructor */
    public function __construct()
    {

        // enqueue our scripts
        add_action('wp_enqueue_scripts', array($this, 'action_wp_enqueue_scripts'));

        // add out ajax actions
        $this->ajax_actions();

    }

    /** frontend enqueued scripts */
    public function action_wp_enqueue_scripts()
    {

        // localize admin ajax
        wp_localize_script('ajax-actions', 'ajax_actions', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
        ));

        // enqueue scripts
        wp_enqueue_script('ajax-actions');

    }


    /** ajax actions */
    public function ajax_actions()
    {

        // admin field postdata ajax actions
        add_action('wp_ajax_field_postdata', [__CLASS__, 'field_postdata']);

        // public field postdata ajax actions
        add_action('wp_ajax_nopriv_field_postdata', [__CLASS__, 'field_postdata']);

    }

    // Field Post Data
    public static function field_postdata()
    {
        global $post;
        $post_id = ($_REQUEST['id']);

        if($post_id){
            $post = get_post($post_id);
            setup_postdata($post);
            get_template_part('ajax/modal','field');
            die();
        }

    }

}

new Frontend();

When I fire the $ajax script below, this is when I get the error feature_ajax is not defined.

But it is defined in the code above.

This script below is my theme-min.js file

// load feature post data
$.ajax({
    cache: false,
    timeout: 8000,
    url: ajax_actions.ajaxurl,
    type: 'POST',
    data: {
        action: 'field_postdata',
        id: post_id
    },
    success: function (data) {
        alert(data);
    }
});

Any help in understanding what i'm doing wrong would be great.

Thanks


Updated Fixed Code

So what I changed to make this work. I was already enqueuing my main-min.js file, so I combined my wp_localize_script using the same handle as my enqueued javascript and it worked.

// register js in footer
$filename = get_template_directory_uri() . '/assets/scripts/main-min.js';
wp_register_script('main-js', $filename, array(), rand(), true);

// localize theme-js ajax actions
wp_localize_script('main-js', 'ajax_actions', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' )
));

// enqueue required scripts
wp_enqueue_script('main-js')
Share Improve this question edited Dec 1, 2018 at 0:36 joshmoto asked Oct 9, 2018 at 1:29 joshmotojoshmoto 4676 silver badges19 bronze badges 1
  • Have you considered using the REST API instead? It's much easier to debug, and more straightforward to register – Tom J Nowell Commented Oct 9, 2018 at 1:57
Add a comment  | 

1 Answer 1

Reset to default 4

To successfully add variable to the window object via wp_localize_script you need to properly invoke three functions in the following sequence:

  1. wp_register_script

  2. wp_localize_script

  3. wp_enqueue_script

In your case you're missing the wp_register_script. In case someone experiences the same issue, follow the code procedures below.

PHP

<?php
    function my_theme_wp_enqueue_scripts() {
        $handle = 'my_handle';

        // Register the script
        wp_register_script($handle, '/path/to/my_script.js');

        // Localize the script with a new data
        wp_localize_script($handle, 'object_name', [
            'ajax_url' => admin_url('admin-ajax.php')
        ]);

        // Enqueue the script
        wp_enqueeu_script($handle);
    }
    add_action('wp_enqueue_scripts', 'my_theme_wp_enqueue_scripts');

Then, you can access the localized object in Javascript

var ajax_url = object_name.ajax_url;
console.log(ajax_url);

Change the $handle variable content as well as the object_name in PHP that makes sense to your application.

Post a comment

comment list (0)

  1. No comments so far