Home > OS >  Display woocommerce notice through Ajax callback on product page
Display woocommerce notice through Ajax callback on product page

Time:06-01

I'm trying to display a woocommerce notice in a product page. The notice should by displayed by an ajax callback function, triggered by a button.

The callback is working correctly, but no notice is being displayed.

Here is my code:

jQuery/AJAX

$(document).ready(function() {
            
    $('#return-button').on('click', function (event) {
        event.preventDefault();

        var id = $(this).val();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'my_custom_function',
                product_id: id
            },
            success: function(response) { 
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

PHP Callback

function my_custom_function() {
    error_log('Function called');

    wc_add_notice("Success!", "notice");
    wc_print_notices();

    wp_die();
}

What is the correct way to do this?

CodePudding user response:

Solution

wc_print_notices() default effect is to echo the HTML code of the notices. The content echoed by my_custom_function corresponds to the response param in the AJAX success function. So it just has to be displayed/inserted in the DOM.

Note: wc_print_notices() can also return the value instead of echoing. This can be done by setting the $return param as true 1.

Here is the working code:

jQuery/AJAX

$(document).ready(function() {
            
    $('#return-button').on('click', function (event) {
        event.preventDefault();

        var id = $(this).val();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'my_custom_function',
                product_id: id
            },
            success: function(response) { 
                $('woocommerce-notices-wrapper').append(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

PHP Callback:

function my_custom_function() {
    error_log('Function called');

    wc_add_notice("Success!", "notice");
    wc_print_notices();
        
    wp_die();
}
  • Related