title: Woocommerce | Clear cart by Ajax
body: <p>I'm trying to set up an AJAX function to clear my cart</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;a onclick="clearCart(this)" data-href="/product-page/" data-productID="182"&gt;Go to Product&lt;/a&gt;
  </code></pre>
  
  <p><strong>JavaScript</strong></p>
  
  <pre><code>function clearCart(d) {
      jQuery(document).ready(function($) {
          var productID = d.getAttribute("data-productID");
          $.ajax({
              url: "addtocart.php",
              data: {productID: productID},
              type: "post",
              success: function(output) {
                  window.location = d.getAttribute("data-href");
                  //alert(output);
              }
          });
      });
  }
  </code></pre>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>if(isset($_POST['productID']) &amp;&amp; !empty($_POST['productID'])) {   
      global $woocommerce;
      $woocommerce-&gt;cart-&gt;empty_cart();
      //echo $_POST['productID'];
  }
  </code></pre>
  
  <p><strong>Result</strong></p>
  
  <ul>
  <li>Internal Server Error caused by 3rd PHP line</li>
  <li>Alerting var output is working (check outcommented code)</li>
  </ul>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>I figured it out by myself and some great help from @MirzaP</p>
  
  <p>JS</p>
  
  <pre><code>      function clearCart(d) {
              jQuery.post(
                  "https://dercampus.ch/wp-admin/admin-ajax.php", 
                  //ajaxurl, 
                  {
                      "action": "clearcart",
                      "data":   d.getAttribute("data-productid")
                  }, 
                  function(){
                      window.location = d.getAttribute("data-href");
                  }
              );
          }
  </code></pre>
  
  <p>PHP</p>
  
  <pre><code>add_action('wp_ajax_nopriv_clearcart',function(){
      global $woocommerce;
      $woocommerce-&gt;cart-&gt;empty_cart();
  });
  </code></pre>