Jump to content
  • Checkout
  • Login
  • Get in touch

osCommerce

The e-commerce.

Sessions, languages and ajax loading


piernas

Recommended Posts

I made an external file that updates the shopping cart without a page reload. It reloads application_top and the needed navbar module and cart totals and replaces the corresponding divs.

 

It works well in every aspect but one: The dummy page loads correctly the session id and cart, but it refreshes the language and takes the default one. I can force to change the language but I don't understand why it keeps the other parameters but changes the language and language_id.

 

Any idea of why it happens?

Link to comment
Share on other sites

Without seeing the code it isn't possible to say for sure but I don't see why those items would have anything to do with the contents of the shopping cart page. Your code should not be changing the url or anything like that. The ajax code would use whatever language that is set. It is just, or should be, refilling a div on the shopping cart page so none of those things should be changed. It might be that you are replacing the whole page, columns and header included, and that would be wrong.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

@@Jack_mcs it's not the case. I just post the standard shopping cart form to a dummy file instead to shopping_cart:

 echo tep_draw_form('cart_quantity', tep_href_link('ext/modules/shopping_cart/cart_update.php', 'action=update_product_ajax')); 

The form is posted with jquery;

 function formPost(product_id) {
        $.post($('form[name="cart_quantity"]').attr("action"), $('form[name="cart_quantity"]').serialize(), function(data) {
  ... replace divs stuff...
 }

Then in the dummy i just have this code:

chdir ("../../../");
include ('includes/application_top.php');
// Added because it's not keeping language:
$language = (null !==$_POST['language']?$_POST['language']:$language);
$languages_id =(null !==$_POST['languages_id']?$_POST['languages_id']:$languages_id);
echo "<!DOCTYPE html>" ."\n";
echo '<meta charset="utf-8">' ."\n";

switch ($_GET['action']) {
      case 'update_product_ajax' :
// here I load the individual modules to replace the original divs

The question is: I was expecting the ajax requested file would be keeping the session language instead of having to pass it from the form, as it keeps the cart.

Link to comment
Share on other sites

That's not how it should be done. In shopping_cart.php, replace all of the code that displays the cart on the page with a div with an id, like

<div id=shopping_cart"></div>

Place that code in some file in the root and name it what you want, like shopping_art_ajax.php. The file should be a php file and it will need to include whatever includes are needed, like application_top. The last line should be

echo json_encode($data);

where $data is a string or array of the contents to be displayed. 

 

Then call that file with jquery like this:

    $.ajax({
      type:  'POST',
      data:  'anydetails to send' ,
      async: false,
      url:"<?php echo tep_href_link('shopping_cart_ajax.php'); ?>",
      dataType: 'json',
      success:function(data) {
           $( "#shopping_cart" ).html( data); 
      }
    }); 

The easiest approach is to add the div with a submit without removing anything else. Then in the new file, just have the following:

$data = "Hello";
echo json_encode($data);

If the code works, when you submit the form using the new button, the dev should display Hello. Then it is just a matter of copying the contents.

 

The above may not work as it is posted but it should be close.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

Thanks @@Jack_mcs my problem are not rewriting the divs, it already does. I do it with jquery instead of pure ajax but the result is the same.

 

The thing that intrigues me is why the session is kept but not the language when you load the file ie:

 

if I access directly the file (not from the shopping cart file but directly) I've put a variable output on it. In that output I see the shopping cart is full, the user is logged... but the language is always the default one, not the chosen one.

Link to comment
Share on other sites

You are changing the post variables with your method. You shouldn't do that. Everything for the page is already set, even the language. There's no reason to have to change that, that I can see.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

Thanks @@Jack_mcs my problem are not rewriting the divs, it already does. I do it with jquery instead of pure ajax but the result is the same.

 

The thing that intrigues me is why the session is kept but not the language when you load the file ie:

 

if I access directly the file (not from the shopping cart file but directly) I've put a variable output on it. In that output I see the shopping cart is full, the user is logged... but the language is always the default one, not the chosen one.

you need to include the corresponding(required) language file in your cart_update.php, in this case your shopping_cart.php language file

 

  require('includes/languages/' . $language . '/shopping_cart.php');

you can also try

  require('includes/languages/' . $_SESSION['language'] . '/shopping_cart.php');

I disagree with jack when he say : That's not how it should be done.

There is no rule for that, and i prefer myself jQuery's $.post() method.

 

Below i will post a file with various "actions" when press an ajax button that do shopping cart actions globally over the whole store (so not just the shopping_cart.php)..

just use it as a reference ;)

<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
require('includes/application_top.php');
require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SHOPPING_CART);

   $messageStack->reset();
if(isset($_POST['products_id'])) {
    $products_id = $_POST['products_id'];
}
    switch ($_POST['action']) {
      // customer wants to update the product quantity in their shopping cart
      case 'update_product' : for ($i=0, $n=sizeof($_POST['products_id']); $i<$n; $i++) {
                                if (in_array($_POST['products_id'][$i], (is_array($_POST['cart_delete']) ? $_POST['cart_delete'] : array()))) {
                                  $cart->remove($_POST['products_id'][$i]);
                                  $messageStack->add('product_action', sprintf(PRODUCT_REMOVED, tep_get_products_name($_POST['products_id'][$i])), 'warning');
                                } else {
                                  $attributes = ($_POST['id'][$_POST['products_id'][$i]]) ? $_POST['id'][$_POST['products_id'][$i]] : '';
                                  $cart->add_cart($_POST['products_id'][$i], $_POST['cart_quantity'][$i], $attributes, false);
                                }
                              }
                             // tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                              break;
      // customer removes a product from their shopping cart
      case 'remove_product' : if (isset($_POST['products_id'])) {
                                $cart->remove($_POST['products_id']);
                                $messageStack->add('product_action', sprintf(PRODUCT_REMOVED, tep_get_products_name($_POST['products_id'])), 'warning');
                              }
                              //tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                              break;
// performed by the 'buy now' button in product listings and review page
   case 'add_buy_now_product' : 
   	if(isset($_POST['products_id'])) {

 if (tep_has_product_attributes($_POST['products_id'])) {
	$product_has_attributes = 'product_has_attributes';
 } else {
 if($_POST['buy_now_quantity']== "") {
 $quantity = 1;
 }else{
 $quantity = $_POST['buy_now_quantity']; 
}
     $cart->add_cart($_POST['products_id'], $cart->get_quantity($_POST['products_id'])+$quantity);
	 
     $messageStack->add('product_action', sprintf(PRODUCT_ADDED, tep_get_products_name((int)$products_id)), 'info');
    
	// We generate the messageStack //
    $ajaxMessageStack  = $messageStack->output('product_action');
	
	}
}	
   break;	
	
	
	
	// performed by the 'buy now' button in product listings and review page
	case 'buy_now':	

	
    if (tep_has_product_attributes($products_id)) {
 	
	/* we have attributes , we use this marker to re-direct to the actual product_info.php product, this is done by the jQuery function */
	$product_has_attributes = 'product_has_attributes';
	
	}else {
    $cart->add_cart($products_id, $cart->get_quantity($products_id)+1);
    $messageStack->add('product_action', sprintf(PRODUCT_ADDED, tep_get_products_name((int)$products_id)), 'info');
    
	/* We generate the messageStack */
    $ajaxMessageStack  = $messageStack->output('product_action');
	
	}
	break;
      // customer removes a product from their shopping cart
      case 'add_wishlist' :
	if(isset($_POST['products_id'])) {
		if(isset($_POST['id'])) {
			$attributes_id = $_POST['id'];
			tep_session_register('attributes_id');
		}
		$wishlist_id = $_POST['products_id'];
		tep_session_register('wishlist_id');
	}
	  if(tep_session_is_registered('wishlist_id')) {
  	$wishList->add_wishlist($wishlist_id, $attributes_id);
	    $product_id = $wishlist_id;
   	tep_session_unregister('wishlist_id');
  	if(tep_session_is_registered('attributes_id')) tep_session_unregister('attributes_id');
  	if(WISHLIST_REDIRECT == 'Yes') {
	  	tep_redirect(tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $product_id));
	  }
  }
	    $messageStack->add('wishlist_action', sprintf(WISHLIST_ADDED, tep_get_products_name((int)$_POST['products_id'])), 'info');
	/* We generate the messageStack */
    $ajaxMessageStack  = $messageStack->output('wishlist_action');
                              break;	
	case 'add_product':	
	if(isset($_POST['products_id']) && is_numeric($_POST['products_id'])) {
    $attributes = isset($_POST['id']) ? $_POST['id'] : '';
    $cart->add_cart($_POST['products_id'], $cart->get_quantity(tep_get_uprid($_POST['products_id'], $attributes)) + $_POST['cart_quantity'], $attributes);	
    $messageStack->add('product_action', sprintf(PRODUCT_ADDED, tep_get_products_name((int)$_POST['products_id'])), 'info');
	
	/* We generate the messageStack */
    $ajaxMessageStack  = $messageStack->output('product_action');
	
	}
	break;
	}
							  
							  

    /* we replace the action for closing the alert message, instead we give it the action to close the dialog */
    $ajaxModalContent  = str_replace("data-dismiss=\"alert\"","data-dismiss=\"modal\"", $ajaxMessageStack);

if ($_POST['action'] == 'add_wishlist') {
    
	   /* we compile global reference data into the 'free_will' array for the json array */	  
		$compiled_products['free_will'] = array(
									 'ajaxModalContent'=> $ajaxModalContent
									 );	
     /* we need to set headers to tell we have no standard content */		
      header('Content-Type: application/json');										 
echo json_encode($compiled_products);									 
	
}else{	
	/* we set the starting marker point always to 0, as we check for it each time we do any cart actions */
    $any_out_of_stock = 0;
	
	/* we call this nifty class function to retrieve all products that where inserted to the cart */
	/* NOTICE: the default oscommerce function does not calculate prices based on customer settings like currency&taxes, we need to do this ourself */
    $products = $cart->get_products();
	
	/* we itterate over the generated array of products that the function above provided us with */
    for ($i=0, $n=sizeof($products); $i<$n; $i++) {
	   
	   /* self explaining */
	   if (STOCK_CHECK == 'true') {
       
	   /* the actual function what does the stock check */
	   $stock_check = tep_check_stock($products[$i]['id'], $products[$i]['quantity']);
       
	   /* if the callback to the above function is not null */
	   if (tep_not_null($stock_check)) {
       
	   /* we got a marker, we go use it later */
	   $any_out_of_stock = 1;
       
	   /* the stock check found a product that has a negative stock corresponding to the client's required quantity */
       $products_name = $products[$i]['name'] . $stock_check;
        }else{
	   
	   /* stock check IS enabled, but we still need the name...Bahh!! */
	   $products_name = $products[$i]['name'];
	   }
      
	  }else{
	  
	  /* stock check is NOT enabled so lets get the name  ....finaly!! */
	  $products_name = $products[$i]['name'];
	   }
	   
	   /* So let's build, we compile only the required data for reference */
	  $compiled_products[] = array('product_id' => $products[$i]['id'],
	                               'product_price' => $currencies->display_price($products[$i]['final_price'], tep_get_tax_rate($products[$i]['tax_class_id']), $products[$i]['quantity']),
								   'product_name' => $products_name);
	  
	  }
	  
	  /* if we found above a product out of stock , we need to generate a message */
      
	  /* we go use our marker from above */
	  if ($any_out_of_stock == 1) {
      
	  /* self explaining */
	  if (STOCK_ALLOW_CHECKOUT == 'true') {
      
	  /* We got the message that there are products out of stock, however we are allowed to checkout */
	  $stock_alert = '<div class="alert alert-warning">' . OUT_OF_STOCK_CAN_CHECKOUT . '</div>';

      } else {
	  
	  /* We got the message that there are products out of stock, here we are NOT allowed to checkout */
      $stock_alert = '<div class="alert alert-danger">' . OUT_OF_STOCK_CANT_CHECKOUT . '</div>';
       }
      }
       if (strpos($product_has_attributes,'product_has_attributes') !== false) {
	   $product_has_attributes = $product_has_attributes;
	   }
	   /* we compile global reference data into the 'free_will' array for the json array */	  
		$compiled_products['free_will'] = array('total' => SUB_TITLE_SUB_TOTAL . ' ' . $currencies->format($cart->show_total()), 
		                             'headcounter' => sprintf(HEADER_CART_CONTENTS, $cart->count_contents()),
									 'subheadcounter' => sprintf(HEADER_CART_HAS_CONTENTS, $cart->count_contents(), $currencies->format($cart->show_total())),
									 'stock_alert' => $stock_alert,
									 'product_has_attributes' => $product_has_attributes,
									 'ajaxModalContent'=> $ajaxModalContent
									 );

      /* if we ever need it we can get a full list of what is inside the cart, keep in mind currencie&taxes are not calculated */
        //$compiled_products['allproducts'] = $products;

     /* we need to set headers to tell we have no standard content */		
      header('Content-Type: application/json');							  

     /* we actual need to check if we have something in the cart ...sigh!!! */
      if ($cart->count_contents() > 0) {

     /*now let us send all the data back to the jQuery function */	
     echo json_encode($compiled_products);
		
    }else{

    /* we have an empty cart.... what i do here!!! */		
    echo '0';		
    
	}
}		
require('includes/application_bottom.php');
}else{
require('includes/application_top.php');
require(DIR_WS_INCLUDES . 'template_top.php');
require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_PRODUCT_INFO);
?>
<div class="contentContainer">
  <div class="contentText">
    <div class="alert alert-warning"><?php echo TEXT_PRODUCT_NOT_FOUND; ?></div>
  </div>

  <div class="pull-right">
    <?php echo tep_draw_button(IMAGE_BUTTON_CONTINUE, 'glyphicon-chevron-right', tep_href_link(FILENAME_DEFAULT)); ?>
  </div>
</div>
<?php
require(DIR_WS_INCLUDES . 'template_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
}
?>

Corresponding ht module (just use it as reference):

<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2014 osCommerce

  Released under the GNU General Public License
*/

  class ht_ajax_cart {
    var $code = 'ht_ajax_cart';
    var $group = 'footer_scripts';
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;

    function ht_ajax_cart() {
      $this->title = MODULE_FOOTER_SCRIPT_AJAXCART_TITLE;
      $this->description = MODULE_FOOTER_SCRIPT_AJAXCART_DESCRIPTION;

      if ( defined('MODULE_FOOTER_SCRIPT_AJAXCART_STATUS') ) {
        $this->sort_order = MODULE_FOOTER_SCRIPT_AJAXCART_SORT_ORDER;
        $this->enabled = (MODULE_FOOTER_SCRIPT_AJAXCART_STATUS == 'True');
      }
    }

    function execute() {
      global $oscTemplate;
	  	$oscTemplate->addBlock('<script>var myvalue; $(".add-product").on("click",function(e){$(".add-product").addClass("ajax-button"); myvalue = "add_product";  })</script>', $this->group);
	  	$oscTemplate->addBlock('<script> $(".wish-list").on("click",function(e){$(".wish-list").addClass("ajax-button"); myvalue = "add_wishlist";  })</script>', $this->group);
	  	$oscTemplate->addBlock('<script> $(".buy_now_qty_product").on("click",function(e){$(".buy_now_qty_product").addClass("ajax-button"); myvalue = "add_buy_now_product";  })</script>', $this->group);

    //$oscTemplate->addBlock('<script>$("form[name=\"shopping_cart_quantity\"]").submit(function(e){var t=$(e.target).attr("action");var n=$(this).serializeArray();n.push({name:"action",value:"update_product"});$.post("ajax_shop_cart.php",n,"json").done(function(e){console.log(e);$("tr.productsincart").removeClass("showme");if(e===0){$("#cart_in_head").html("<li id=\"cart_in_head\" class=\"nav navbar-text\">"+headerTextNoContent+"</li>");$("#checkout_head").remove();$(".ajax_response").remove();$(".contentText").html(""+cartTextEmpty+"<p class=\"text-right\">"+buttonContinueDefault+"</p>")}else{$.when($.each(e,function(e,t){$("tr").closest("[data-product-row=\'"+t.product_id+"\']").addClass("showme");$("strong").closest("[data-id-name=\'"+t.product_id+"\']").html(t.product_name);$("strong").closest("[data-pid=\'"+t.product_id+"\']").html(t.product_price)})).done(function(){$("tr.productsincart").not(".showme").remove();$("#cart_in_head a.dropdown-toggle").html(e["free_will"].headcounter);$("li.ajax_counter a").html(e["free_will"].subheadcounter);$("#ajax_price_total").html(e["free_will"].total).fadeOut(400).fadeIn(600);$("div.stock_control").html(e["free_will"].stock_alert).fadeOut(1e3).fadeIn(600).fadeOut(1e3).fadeIn(600)})}});return false})</script>', $this->group);
	$oscTemplate->addBlock('<script>function buildUpCartModal(){$("#bodyWrapper").prepend("<div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-body\"></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">"+buttonContinue+"</button><a href=\""+cartLink+"\" class=\"btn btn-primary\" role=\"button\"><span class=\"glyphicon glyphicon-shopping-cart\"></span>" +headerViewCart+"</a></div></div></div></div>");$("#myModal").modal("show")}</script>', $this->group);
	$oscTemplate->addBlock('<script>function buildUpWishListModal(){$("#bodyWrapper").prepend("<div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-body\"></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">"+buttonContinue+"</button><a href=\""+wishListLink+"\" class=\"btn btn-warning\" role=\"button\"><span class=\"glyphicon glyphicon-heart\"></span>"  +ViewWishList+"</a></div></div></div></div>");$("#myModal").modal("show")}</script>', $this->group);
		$oscTemplate->addBlock('<script>$("form[name=\"form_buy_now_product\"]").submit(function(e){$(".ajax-button").button(""); if(myvalue === "add_buy_now_product") {buildUpCartModal();} if(myvalue === "add_wishlist") {buildUpWishListModal();}var t=$(this).serializeArray();t.push({name:"action",value:myvalue});$.post("ajax_shop_cart.php",t,"json").done(function(e){ if(myvalue === "add_buy_now_product") {$("#cart_in_head").removeClass("nav navbar-text").addClass("dropdown");$("#cart_in_head").html("<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">"+e["free_will"].headcounter+"</a><ul class=\"dropdown-menu\"><li class=\"ajax_counter\"><a href=\""+cartLink+"\">"+e["free_will"].subheadcounter+"</a></li><li class=\"divider\"></li><li><a href=\""+cartLink+"\">"+headerViewCart+"</a></li><li class=\"divider\"></li><li id=\"checkout_head\"><a href=\""+checkOutShippingSll+"\">"+headerTextCheckout+"</a></li></ul>");} $(".modal-body").html(e["free_will"].ajaxModalContent)});return false})</script>', $this->group);

	$oscTemplate->addBlock('<script>$("form[name=\"cart_quantity\"]").submit(function(e){$(".ajax-button").button(""); if(myvalue === "add_product") {buildUpCartModal();} if(myvalue === "add_wishlist") {buildUpWishListModal();}var t=$(this).serializeArray();t.push({name:"action",value:myvalue});$.post("ajax_shop_cart.php",t,"json").done(function(e){ if(myvalue === "add_product") {$("#cart_in_head").removeClass("nav navbar-text").addClass("dropdown");$("#cart_in_head").html("<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">"+e["free_will"].headcounter+"</a><ul class=\"dropdown-menu\"><li class=\"ajax_counter\"><a href=\""+cartLink+"\">"+e["free_will"].subheadcounter+"</a></li><li class=\"divider\"></li><li><a href=\""+cartLink+"\">"+headerViewCart+"</a></li><li class=\"divider\"></li><li id=\"checkout_head\"><a href=\""+checkOutShippingSll+"\">"+headerTextCheckout+"</a></li></ul>");} $(".modal-body").html(e["free_will"].ajaxModalContent)});return false})</script>', $this->group);
	$oscTemplate->addBlock('<script>$("a.buy_now").on("click",function(e){var t=$(e.target).data("id-product");$(e.target).addClass("ajax-button");$(e.target).attr("data-loading-text","Processing");$(".ajax-button").button("");$.post("ajax_shop_cart.php",{products_id:t,action:"buy_now"},"json").done(function(e){if(e["free_will"].product_has_attributes=="product_has_attributes"){window.location.href="product_info.php?products_id="+t}else{buildUpCartModal();$("#cart_in_head").removeClass("nav navbar-text").addClass("dropdown");$("#cart_in_head").html("<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">"+e["free_will"].headcounter+"</a><ul class=\"dropdown-menu\"><li class=\"ajax_counter\"><a href=\""+cartLink+"\">"+e["free_will"].subheadcounter+"</a></li><li class=\"divider\"></li><li><a href=\""+cartLink+"\">"+headerViewCart+"</a></li><li class=\"divider\"></li><li id=\"checkout_head\"><a href=\""+checkOutShippingSll+"\">"+headerTextCheckout+"</a></li></ul>");$(".modal-body").html(e["free_will"].ajaxModalContent)}});return false})</script>', $this->group);

    //$oscTemplate->addBlock('<script>$(".remove_product").on("click",function(){var e=$(this).data("id-product");$.post("ajax_shop_cart.php",{products_id:e,action:"remove_product"},"json").done(function(e){console.log(e);$("tr.productsincart").removeClass("showme");if(e===0){$("#cart_in_head").html("<li id=\"cart_in_head\" class=\"nav navbar-text\">"+headerTextNoContent+"</li>");$("#checkout_head").remove();$(".ajax_response").remove();$(".contentText").html(""+cartTextEmpty+"<p class=\"text-right\">"+buttonContinueDefault+"</p>")}else{$.when($.each(e,function(e,t){$("tr").closest("[data-product-row=\'"+t.product_id+"\']").addClass("showme");$("strong").closest("[data-pid=\'"+t.product_id+"\']").html(t.product_price);$("#ajax_price_total").html(t.total).fadeOut(400).fadeIn(600)})).done(function(){$("tr.productsincart").not(".showme").remove();$("#cart_in_head a.dropdown-toggle").html(e["free_will"].headcounter);$("li.ajax_counter a").html(e["free_will"].subheadcounter);$("#ajax_price_total").html(e["free_will"].total).fadeOut(400).fadeIn(600);$("div.stock_control").html(e["free_will"].stock_alert).fadeOut(1e3).fadeIn(600).fadeOut(1e3).fadeIn(600)})}});return false})</script>', $this->group);
    $oscTemplate->addBlock('<script>$("body").on("hidden.bs.modal",function(){$(".ajax-button").button("reset").removeClass("ajax-button");$("#myModal").remove()})</script>', $this->group);
	$oscTemplate->addBlock('<script>$(".tooltip_cookie").tooltip()</script>', $this->group);

	}

    function isEnabled() {
      return $this->enabled;
    }

    function check() {
      return defined('MODULE_FOOTER_SCRIPT_AJAXCART_STATUS');
    }

    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Ajax Module', 'MODULE_FOOTER_SCRIPT_AJAXCART_STATUS', 'True', 'Enable the ajax cart?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_FOOTER_SCRIPT_AJAXCART_SORT_ORDER', '0', 'Sort order of script execution. Lowest is displayed first.', '6', '0', now())");
    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      return array('MODULE_FOOTER_SCRIPT_AJAXCART_STATUS', 'MODULE_FOOTER_SCRIPT_AJAXCART_SORT_ORDER');
    }
  }
?>

Link to comment
Share on other sites

 

@@wHiTeHaT I disagree with jack when he say : That's not how it should be done.

There is no rule for that, and i prefer myself jQuery's $.post() method.

To be clear, I was referring to the code about changing post variables and resetting the language and language ID. Nothing in the shop should do that except when meaning to change the language or currency. But for the shopping cart, why would one change either? Maybe I'm missing something. As for handling the update, there are, of course, other ways of doing it. There are always other way in code. I think one would run into less problems, in general, using ajax with json but that's just my preference.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

@@Jack_mcs ok.. all clear ;)

 It might be that you are replacing the whole page, columns and header included, and that would be wrong.

That is what i was also thinking, and it is not in the spirit of what ajax is for. (reduce server resources and make the user experience more friendly).

But i like surprises :) 

Link to comment
Share on other sites

@@wHiTeHaT @@Jack_mcs the problem is not in the div loading but in the session handling. I've found something strange while

 

Maybe I'm not understandong how the php sessions work or there is another problem on my setup. While debugging my problem I found another thing I don't understand, but can you please confirm if this is normal:

 

- Blank oscommerce setup, no addons, no extra languages, nothing added but this code at application_bottom right before the tep_session_close () statement:

echo '<pre>';
var_dump($_SESSION);
echo '</pre>';

Steps:

1- I add something to shopping_cart.

2- Remove the item from shopping_cart

 

After step 2 I obtain the following in the footer:

E:\0\includes\application_bottom.php:16:
array (size=7)
  'sessiontoken' => string 'f414fdfe3f8e0fad36446e8c90662d6b' (length=32)
  'cart' => 
    object(shoppingCart)[4]
      public 'contents' => 
        array (size=0)
          empty
      public 'total' => float 29.99
      public 'weight' => float 7
      public 'cartID' => string '37642' (length=5)
      public 'content_type' => boolean false
  'language' => string 'english' (length=7)
  'languages_id' => string '1' (length=1)
  'currency' => string 'USD' (length=3)
  'navigation' => 
    object(navigationHistory)[5]
      public 'path' => 
        array (size=1)
          0 => 
            array (size=4)
              ...
      public 'snapshot' => 
        array (size=0)
          empty
  'new_products_id_in_cart' => int 10

Shopping_cart is empty but echoing $_SESSION shows "total" and "weight" otheer than 0. Is this the normal behavior?

Link to comment
Share on other sites

If you remove the changes you have made to get back to the standard setup, the cart work correctly? If not, the problem is most likely in your configure file. If it does, then you need to troubleshoot your new code to find where it is changing. I would leave the code as it is and add a second form with just the hello I mentioned. If it fails with that, then your basic code is wrong.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

I may not have been clear. Please do this:

 

- Remove all of your changes to do with the shopping cart.

- Add something to the cart. Set the language and currency to whatever you like,

- Login to your account..

- Go to the shopping cart page.

 

Is whatever you added to the cart still there? Is the language and currency correct?

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

@@Jack_mcs I already located the problem. It's on multilingual support of seo URLS 5 contrib; my code has nohing to do with the language problem and it wa sonly a language problem, nothing with the cart.

 

But in the process of tracing the error I found a second (maybe not a problem, let's call it a strange behavior) in oscommerce.

 

Can you please do the following:

 

1- I add something to shopping_cart.

2- Remove the item from shopping_cart

3- inspect the $SESSION['cart'] variable

 

Does it contain a 'total' and/or a 'weight' value?

I suspect those variables are not being zero-ed when you remove the last item of the cart.

Link to comment
Share on other sites

Then that has nothing to do with this thread. You should post a new question in the SEO 5 support thread.

 

I think you misreaded my post. The issue I mention happens without SEO URLS installed.

 

Can you please confirm this behavior?

 

1- New oscommerce 2.3.4 setup - no contribs installed at all.

2- Add something to shopping_cart.

3- Remove the item from shopping_cart

4- inspect the $SESSION['cart'] variable

 

Does it contain a 'total' and/or a 'weight' value?

Link to comment
Share on other sites

One f the problems with SEO 5 is that turning it off doesn't really remove it from the code so I would still suspect it. But are you saying that if you remove all of the changes you made for the shopping cart that the cart works fine with the languages and currencies, or any other problem you may be seeing? You have to be sure the core code is working or you will never get the code you are adding to work properly. It doesn't sound like you've done that.

Support Links:

For Hire: Contact me for anything you need help with for your shop: upgrading, hosting, repairs, code written, etc.

Get the latest versions of my addons

Recommended SEO Addons

Link to comment
Share on other sites

@@piernas just tested and you are right.

 

you can test an untested (lol) fix.

 

Goto classes/shopping_cart.php find function remove($......

 

BEFORE

// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
      $this->cartID = $this->generate_cart_id();
    }

add:

$this->calculate();

So it looks like:

      $this->calculate();

// assign a temporary unique ID to the order contents to prevent hack attempts during the checkout procedure
      $this->cartID = $this->generate_cart_id();
    }

I do not know for now what it do when do a full checkout.

Link to comment
Share on other sites

Interestingly, I cannot recreate this.  

 

Add to cart:

 

 

["total"]=>float(99)
["weight"]=>float(1)
["cartID"]=>string(5) "63247"
["content_type"]=>bool(false)

 

Then remove from cart:

 

 

["total"]=>int(0)
["weight"]=>int(0)
["cartID"]=>string(5) "99126"
["content_type"]=>bool(false)
Link to comment
Share on other sites

One f the problems with SEO 5 is that turning it off doesn't really remove it from the code so I would still suspect it.

 

Again, I think you misreaded. No code added, brand new install. Can't remove anything that I didn't add :)

 

@@wHiTeHaT thanks for te fix. I think it does not interfer with any stock oscommerce process but obviously it shouldn't work that way.

 

@@burt I've done it on a 2.3.4 BSS edge. Will test o a 2.2 setup to see if the thing happened there too.

Link to comment
Share on other sites

@@burt It also happens on an old 2.2 shop:

  ["cart"]=>
  &object(shoppingCart)#1 (5) {
    ["contents"]=>
    array(0) {
    }
    ["total"]=>
    float(55)
    ["weight"]=>
    float(1.5)
    ["cartID"]=>
    string(5) "22143"
    ["content_type"]=>
    bool(false)
Link to comment
Share on other sites

Link to comment
Share on other sites

Tested on :

live server php7 (unix),

local server php7 & php 5.6.19 (Windows/Wamp).

i can confirm piernas is right.

 

Still i assume it have to do with server settings.

There is nowhere in the shopping_cart.php class told to unset these 2 vars, when remove product. i am more surprised Gary's testing result.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...