N
N
Nohaga2019-09-28 13:25:18
WordPress
Nohaga, 2019-09-28 13:25:18

How to pass function parameters via ajax?

Here is the php function code to add item to cart

add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
    function myajax($product_id, $qty) {
    global $woocommerce;
    $woocommerce->cart->add_to_cart($product_id, $qty);
    die();
    }

I found the code on the Internet

jQuery(document).ready(function($){     
    $.ajax({
        url: "wp-admin/admin-ajax.php",
        data: 'myajax'
    });
});


How to pass $product_id and $qty parameters to myajax() function in ajax request? Maybe the request is not correct at all, in general, the goal is to add the product to the cart through Ajax, I use this function and parameters.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex-1917, 2019-09-28
@alex-1917

the code is initially incorrect, there is no action parameter

jQuery(document).ready(function($){     
   $.ajax({
      url: "wp-admin/admin-ajax.php",
      data: {
         action: 'myajax',
         product_id: $product_id,
         qty : $qty,
      };
   });
});

And in the handler, catch it like this:
function myajax() {
   $product_id= intval( $_POST['product_id'] );
   $qty= intval( $_POST['qty'] );
   global $woocommerce;
   $woocommerce->cart->add_to_cart($product_id, $qty);
   die();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question