skip to Main Content

Using wordpress plugin "Code Snippets" – How could I take a php function like the one below and turn it into an Ajax button inside of elementor?

Essentially… i’d really like to know how I can take any PHP function and execute it from an Ajax button.

Thanks so much for your help! Clearly I have no idea what I’m taking about.

Function:

add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    if ( isset( $_GET['clear-cart'] ) ) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}

2

Answers


  1. you can put the php function inside a php file and do a ajax call to execute the php script and you can use the response data like below:

    $.ajax({
            url: "functionfile.php",
            type: "post",
            data: values ,
            success: function (response) {
    
               // You will get response from your PHP page (what you echo or print)
            },
            error: function(jqXHR, textStatus, errorThrown) {
               console.log(textStatus, errorThrown);
            }
        });
    
    Login or Signup to reply.
  2. You need to checkout the code here I created the admin hook to clear the cart using ajax

    <?php
    
    // Ajax Action 
    add_action('wp_ajax_customAjax', 'customAjax');
    add_action('wp_ajax_nopriv_customAjax', 'customAjax');
    function customAjax() {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
        echo json_encode(array('msg' => 'done'));
        exit;
    }
    
    // Ajax JavaScript Call
    add_action( 'wp_footer', 'clearCart' );
    function clearCart()
    {
        ?>
        <script>
        function customAjax() {
            var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
            jQuery.post(
                my_repeater_ajax_url, {
                    'action': 'customAjax',
                },
                function (json) {
                    if(json['msg'] == 'done')
                    {
                        location.reload();
                    }
                },
                'json'
            );
        }
        </script>
        <?php
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search