0

I'm working on triggering a function through AJAX after clicking in a specific element, but it does not work.

Not even a simple echo "Test" works in the function, it just does not seem to run, yet the ajax call is executed and works. You can check in developer tools on this website https://woocommerce-842277-3644151.cloudwaysapps.com/

  1. Go to product page
  2. Add to cart
  3. On the page where the image of two football players are just click on the image somewhere and check the Network tab in Developer tools, the payload etc. is present.

This is my code

functions.php (enqueue and localize)

wp_enqueue_script( 'treblecars-ajaxapp', get_template_directory_uri() . '/js/ajaxapp.js', array(), _S_VERSION, true );
wp_localize_script( 'treblecars-ajaxapp', 'trblAjax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

ajaxapp.js

jQuery(document).ready(function($){

  // Fill coords on active item and move to the next item
  $('#botbSpotImage').click(function(e) {
    var cart = [];          // Will retrieve every cart item's meta

    $('.botbSpotEvenWaCUnplayed').each(function(){
      //This object will store your meta data and be pushed into kart array
      var kitm = {
        'p' : $(this).attr('data-product-id'),
        'm' : $(this).find('input[name="coords_input"]').val(),
        'k' : $(this).attr('data-entry-id')
      };

      cart.push(kitm);
    });

    $.ajax({
      url: trblAjax.ajaxurl,
      data: {
        'action': 'update_cart_item_meta',
        'k': cart
      },
      success:function(data){
        console.log(data);
      },
      error:function(errorThrown){
        console.log(errorThrown);
      }
    });

  });
});

functions.php (actual function I want to run)

function update_cart_item_meta(){
    global $woocommerce;
    $cart = $woocommerce->cart->cart_contents;
    $updt = Array();

    foreach ($_REQUEST['k'] AS $item){
        $product = new stdClass();
        $updtCL = new stdClass();
        $product->{'id'} = $item['p'];          //This is product id
        $product->{'mymeta'} = $item['m'];      //This is metadata
        $updtCL->{'krtkey'} = $item['k'];       //This is product key in cart
        $updtCL->{'meta'} = $product;
        $updt[] = $updtCL;
    }

    // cycle the cart replace the meta of the correspondant key
    foreach ($cart as $key => $item) {
        foreach($updt as $updtitem){
                if($key == $updtitem->krtkey){      // if this kart item corresponds with the received, the meta data is updated
                        // Update the content of the kart
                        $woocommerce->cart->cart_contents[$key]['coordinates'] = $updtitem->meta;
                }
        }
    }

    // This is the magic: With this function, the modified object gets saved.
    $woocommerce->cart->set_session();

    wp_die();
}

add_action('wp_ajax_update_cart_item_meta', 'update_cart_item_meta');
add_action('wp_ajax_nopriv_update_cart_item_meta', 'update_cart_item_meta'); 
Bayron2304
  • 117
  • 2
  • 13
  • Loic! I summoned you :D. But on a serious note, this does not work, unfortunately. The whole issue to get over first is the function does not even trigger in the first place. A simple `echo "Testing";` does not even do anything. Any ideas as to why? – Bayron2304 Jun 26 '23 at 17:27
  • Tried it but also does not work. I've even tried the simplest of AJAX calls and functions but it does not trigger. I doubt it's got to do with anything URL related as the payload is shown in Developer tools `action: update_cart_item_meta k[0][p]: 12 k[0][m]: X 746, Y 38 k[0][k]: 8c449707a8b0e7d8629a4e361dc42e20` – Bayron2304 Jun 26 '23 at 17:46
  • Maybe just for a testing period, instead of enqueuing/localize your script, try to embed it in the footer using a function hooked in `wp_footer` like in [this answer](https://stackoverflow.com/questions/65717674/set-postcode-from-a-field-for-guests-and-customers-in-woocommerce/65719716#65719716) … Then you could make a simplified code example that is testable in your question. – LoicTheAztec Jun 26 '23 at 17:59
  • That worked, the function is running now. Any clue as to how I can get this to run by enqueueing and localizing? – Bayron2304 Jun 26 '23 at 18:25
  • Instead of enqueuing/localizing you can use the WooCommerce function [`wc_enqueue_js()`](https://github.com/woocommerce/woocommerce/blob/release/7.8/plugins/woocommerce/includes/wc-core-functions.php#L991-L1004) like in [this answer](https://stackoverflow.com/a/76510682/3730754)… but don't start your jQuery code with `jQuery(document).ready(function($){` as this WooCommerce function will do it by itself… – LoicTheAztec Jun 26 '23 at 18:38

1 Answers1

0

Got this to work thanks to @LoicTheAztec by suggesting it to enqueue my AJAX script in the footer. Check his comment for more information.

Bayron2304
  • 117
  • 2
  • 13