Ajax problem in add to cart form


I have tried using the built in interface to enable AJAX callbacks for my add to cart form but it isnt working. I made a custom list of products with an "add to cart" button next to them but for some reason the whole page reloads.

The site is here: http://tinyurl.com/a8bsmjh

Since the front page is built in one single page with information (only ajax calls in colorbox) its pretty important that one can add new products without reloading the whole page.

Anyone has any idea on what files to modify etc to make this work? :)

Posted: Jan 10, 2013


victorv on January 10, 2013

Found one solution.

It works, but is not very maintainable. All feedback is welcome. It might also have some issues with the updating of the cart. But ill write another answer and submit code for that fix l8er.

Here is a copy of my findings from this page: http://www.drupalcommerce.org/discussions/2628/add-cart-ajax
"I made it the easy way and put this in my template.php file... but when i clear the caches it only shows the text "array".

If i just upload it and dont clear caches it works like a charm. Any ideas?"

/* ----------Cart manipulation------------------------------ */
function <b>MYTHEME</b>_form_alter(&$form, &$form_state, $form_id) {
  // Add ajax property to Add to Cart button
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit'] = array(
      '#value' => t('BUY TEXT'),
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => '<b>MYTHEME</b>_form',
        'wrapper' => 'block-commerce-cart-cart',
        'effect' => 'fade',
        'progress' => array('type' => 'throbber', 'message' => ''),
    $form['#submit'][] = '<b>MYTHEME</b>_form_rebuild_submit';

function ishop_form_rebuild_submit($form, &$form_state){
  $form_state['rebuild'] = TRUE;

function MYTHEME_form($form, &$form_state){
  global $user;
  $order_id = commerce_cart_order_id($user->uid);
  $cart =  commerce_embed_view('commerce_cart_block', 'default', array($order_id));
  $commands = array();

  $commands[] = ajax_command_replace('#block-commerce-cart-cart .view-commerce-cart-block', $cart);
  $commands[] = ajax_command_replace('#block-commerce-cart-cart .cart-empty-block', $cart);
  $commands[] = ajax_command_after('.'.$form['#attributes']['class'][1],theme('status_messages'));
  return array('#type' => 'ajax', '#commands' => $commands);
/* --------------------------------------------------------- */