Home > Software design >  How to Resolve Wordpress AJAX Error - "my_ajax_obj not defined"?
How to Resolve Wordpress AJAX Error - "my_ajax_obj not defined"?

Time:12-29

I am trying to set up an AJAX call in Wordpress and I keep getting the console error: "my_ajax_obj not defined." Right now, I am building an LMS using a custom theme in Wordpress and when a video is watched, the goal is to trigger a php script to add to a user's meta data.

So far, this is what I have: when a lesson video is watched, the function

lesson_watched_call()

is called. I currently have my AJAX script in the file my-ajax-script.js and in that file, I have what is below.

function lesson_watched_call() {  
        console.log('Lesson watched fn called.')
        $.post(my_ajax_obj.ajax_url, {
            _ajax_nonce: my_ajax_obj.nonce,  // nonce
            action: "lesson_watched", // action call
            lastValue_php: lastValue // data
        });
    }

In my functions.php file, I have the enqueueing and localizing functions.

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {

  wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

  wp_localize_script( 'ajax-script', 'my_ajax_object',
          array( 'ajax_url' => admin_url( 'admin-ajax.php' ),
                 'nonce'    => wp_create_nonce( 'lesson_nonce_value' ),
          ) 
        );
}

My php function for the AJAX action is currently in my footer.php file.

add_action('wp_ajax_lesson_watched', 'add_lesson');
function add_lesson() {
    $lastValue_php = wp_unsplash( $_POST['lastValue_php'] );
      
    echo 'Howdy partner :)';
      
    wp_die(); // Ends all AJAX handlers
}

I have tried several formats, but all of them end up with the same console error saying that my_ajax_obj is not defined. Maybe there is something that I am overlooking?

Thank you for your time,

Ian

CodePudding user response:

you are defining in php my_ajax_object and you are trying to call in js my_ajax_obj

change your php code to:

wp_localize_script( 'ajax-script', 'my_ajax_obj',
          array( 'ajax_url' => admin_url( 'admin-ajax.php' ),
                 'nonce'    => wp_create_nonce( 'lesson_nonce_value' ),
          ) 
        );

Also, for enqueueing on the front end you should be using the wp_enqueue_scripts hook. You are using the admin_enqueue_scripts.

your code should be:

add_action( 'wp_enqueue_scripts', 'my_enqueue' );

and your ajax function to show on front end as well add the wp_ajax_nopriv hook

add_action('wp_ajax_nopriv_lesson_watched', 'add_lesson');
  • Related