0

Am trying to run Ajax call in my Woocommerce checkout page, but am always getting the full html of same page return.

add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
    wp_enqueue_script( 'theme_scripts', get_stylesheet_directory_uri() . '/assets/js/theme.js', array(), '1.0.0', true );
    wp_localize_script( 'theme_scripts', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );  
}

Am calling the ajax when address is changed

add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
        (function($){
   $( document.body ).on( 'updated_checkout', function(){
        $.ajax({
                url: my_ajax_object.ajaxurl,
                data: {
                    'action':'example_ajax_request',
                },
                success:function(data) {
                    console.log(data);
                },
                error: function(errorThrown){
                    console.log(errorThrown);
                }
            }); 
    });
})(jQuery); 
</script>
<?php
}

The example Function

  function example_ajax_request() {
echo 'ok';
         wp_send_json_success( 'It works' );
die();
    }

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

1 Answer 1

0

Fixed by using 'nonce'

refer to this sample project

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Sep 16, 2022 at 12:26

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