Jump to content
  • Checkout
  • Login
  • Get in touch

osCommerce

The e-commerce.

jQuery/Ajax Shopping Cart


delete13

Recommended Posts

 

@@Dr. Rolex

 

I've installed this mod onto a clean oscommerce 2.3.4 install and everything works well, I've checked with IE 11, Chrome, Safari, Opera and Firefox and all seems fine - I'm not really bothered with IE and below.

 

But I am finding it quite taxing add the code to the modules.   Please could you have a look at this code and give me advice on how and where to add your code, I'm really struggling with this :( I'd really appreciate this very much

 

This should work, assuming parameters can be put on the fifth position of the tep_image_cdn function.

<?php
/*
 * $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2010 osCommerce Released under the GNU General Public License
 */
  if ( ( ! isset ( $new_products_category_id ) ) || ( $new_products_category_id == '0' ) ) {
    $new_products_query = tep_db_query ( "select p.products_id, p.products_image, p.products_tax_class_id, pd.products_name, if(s.status, s.specials_new_products_price, p.products_price) as products_price from " . TABLE_PRODUCTS . " p left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_featured = '1' and p.products_id = pd.products_id and pd.language_id = '" . ( int ) $languages_id . "' order by RAND() limit " . MAX_DISPLAY_NEW_PRODUCTS );
  } else {
    $new_products_query = tep_db_query ( "select distinct p.products_id, p.products_image, p.products_tax_class_id, pd.products_name, if(s.status, s.specials_new_products_price, p.products_price) as products_price from " . TABLE_PRODUCTS . " p left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_CATEGORIES . " c where p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and c.parent_id = '" . ( int ) $new_products_category_id . "' and p.products_status = '1' and p.products_featured = '1' and p.products_id = pd.products_id and pd.language_id = '" . ( int ) $languages_id . "' order by RAND() limit " . MAX_DISPLAY_NEW_PRODUCTS );
  }
  $num_new_products = tep_db_num_rows ( $new_products_query );
  if ( $num_new_products > 0 ) {
    $counter = 0;
    $col = 0;
    $new_prods_content = '<div class="grid-100 grid-parent">';
    while ( $new_products = tep_db_fetch_array ( $new_products_query ) ) {
      $counter ++;
      if ( $col === 0 ) {
        $new_prods_content .= '<div class="grid-33 mobile-grid-100 tablet-grid-33">';
      }
      $new_prods_content .= '<div class="border grid-100 mobile-grid-100">
  <div class="grid-100 mobile-grid-100" style="text-align:center">
    <div class="product_name box mobile-grid-100">
      <a href="' . tep_href_link( FILENAME_PRODUCT_INFO, 'products_id=' . $new_products['products_id'] ) . '">' . $new_products['products_name'] . '</a>
    </div>
    <div class="product_img box mobile-grid-100">' .
        //     . tep_image_cdn(DIR_WS_IMAGES_CDN . $new_products ['products_image'], $new_products['products_name'],SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '
      tep_draw_form( 'cart_quantity-prodnew-' . $new_products['products_id'] . '', tep_href_link( FILENAME_SHOPPING_CART, 'products_id='.$new_products['products_id'] . '&action=add_product' ) ) . tep_draw_hidden_field( 'products_id', $new_products['products_id'] ) . '<h5 id="pi-product-info-'. (int)$new_products['products_id'].'" style="display:none"><a href="' . tep_href_link( FILENAME_DEFAULT, tep_get_all_get_params( array( 'action' ) ) . 'products_id=' . (int)$new_products['products_id'] ) . '" title="' . $new_products['products_name'] . '">' . $new_products['products_name'] . '</a></h5>' .

        tep_image_cdn( DIR_WS_IMAGES_CDN . $new_products ['products_image'], $new_products['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT, 'class="draggable" rel="'.(int)$new_products['products_id'].'" id="cart-image-' . (int)$new_products['products_id'] . '" data-id="prodnew-"' ) .
        '</form>
    </div>
  </div>
  <div class="grid-100 mobile-grid-100 tablet-grid-100">
    <div class="product_price box grid-50 mobile-grid-100 tablet-grid-50">
      <div class="prodprice mobile-grid-100 tablet-grid-50">
        ' . $currencies->display_price ( $new_products['products_price'], tep_get_tax_rate ( $new_products['products_tax_class_id'] ) ) . '
      </div>
    </div>
    <div class="product_more_info box grid-50 mobile-grid-100 tablet-grid-50">
      <div class="moreinfo mobile-grid-100 tablet-grid-50">
        <a href="' . tep_href_link( FILENAME_PRODUCT_INFO, 'products_id=' . $new_products['products_id'] ) . '">' . READ_MORE . '</a>
      </div>
    </div>
  </div>
  </div>';
      $col ++;
      if ( ( $col > 0 ) || ( $counter == $num_new_products ) ) {
        $new_prods_content .= '</div>';
        $col = 0;
      }
    }
    $new_prods_content .= '</div>';
  ?>
  <div class="contentText">
    <?php echo $new_prods_content; ?>
  </div>
  <?php
  }

Link to comment
Share on other sites

  • 4 months later...

I have a following questions regarding this add-on.

 

1. The quantity input function works only if you click the plus or minus icons. Can that be recoded so that it allows people to input directly a number into the input field AND/OR use the plus/minus icons? (change, paste, keyup)

 

2. This whole AJAX thing works only if the bm_shopping_cart.php is activated and used. What need to be changed so that the AJAX feature works only on the shopping_cart.php site without all the other stuff. No flying, no dragging, no shopping cart in the left or right column?

Link to comment
Share on other sites

I have a following questions regarding this add-on.

 

1. The quantity input function works only if you click the plus or minus icons. Can that be recoded so that it allows people to input directly a number into the input field AND/OR use the plus/minus icons? (change, paste, keyup)

 

Yes, all you need is a regular submit button. In fact, you can change the quantity and then press ENTER to post the form.

 

However, if you want a keyup/keydown functionality then you need to add that as an event handler.

There's a lot that could be done to improve this Add-On, I didn't know very much about jQuery/JS when I coded it.

 

I wanted to get delete13's original Add-On for osC 2.2 to just work, I didn't care how the result would look as long as it did what I wanted it to do.  :thumbsup: 

 

Here's a somewhat ugly example on how to get a layout with a jQuery-UI themed submit button.

In shopping_cart.php find this:

      $info_box_contents[$cur_row][] = array('params' => 'class="cart-qty" ',
                                             'text' =>
                                             '<a href="#" class="update-qty moins" style="visibility:hidden;" rel="' . $products[$i]['id'] . '">' . tep_image(DIR_WS_ICONS . 'moins.png') . '</a>' .
                                             tep_draw_input_field('cart_quantity[]', $products[$i]['quantity'], 'size="4" id="pl' . $products[$i]['id'] . '"' ) . tep_draw_hidden_field('products_id[]', $products[$i]['id']) .
                                              '<a href="#" class="update-qty plus" style="visibility:hidden;" rel="' . $products[$i]['id'] . '">' . tep_image(DIR_WS_ICONS . 'plus.png')  . '</a>'
                                             );

Replace With:

      $info_box_contents[$cur_row][] = array('params' => 'class="cart-qty" ',
                                             'align' => 'center',
                                             'text' =>
                                             '<div id="buttonset"><span class="update-qty moins" rel="' . $products[$i]['id'] . '">' .

                                             '<button type="button" data-icons="ui-icon-minusthick" data-text="false" class="tdb ui-state-default ui-corner-all ui-button ui-widget ui-button-icon-only ui-priority-primary" role="button" title="" style="height: 26px;" rel="' . $products[$i]['id'] . '"></button></span>' .

                                             '<span>' . tep_draw_input_field('cart_quantity[]', $products[$i]['quantity'], 'style="border-radius: 20px;width: 26px;height: 26px;text-align: center;vertical-align: top;margin: 0 5px 5px 5px;" id="pl' . $products[$i]['id'] . '"' ) . tep_draw_hidden_field('products_id[]', $products[$i]['id']) . '</span>' .
                                              '<span class="update-qty plus" rel="' . $products[$i]['id'] . '">' .

                                             '<button type="button" data-priority="primary" data-icons="ui-icon-plusthick" data-text="false" class="tdb tdb ui-state-default ui-corner-all ui-button ui-widget ui-button-icon-only ui-priority-primary" ""="" role="button" title="" style="height: 26px;"></button></span>' .

                                             '<br><button type="submit" data-priority="primary" data-icons="ui-icon-check" data-text="false" class="tdb tdb ui-state-default ui-corner-all ui-button ui-widget ui-button-icon-only ui-priority-primary" ""="" role="button" title="" style="height: 26px;"></button></div>'
                                             );

Find This:

<script type="text/javascript" src="ext/modules/shopping_cart/jquery-oscart.js?1100"></script>

Replace With:

<script>
// Fixes jQuery Buttons
function btnInfo(data_priority, data_icons) {
    if (data_priority == "primary") return {
        primary: data_icons
    };
    else return {
        secondary: data_icons
    }
}
$(function(){
$(".tdb").each(function(i) {
    var data_priority = $(this).attr("data-priority"),
        data_icons = $(this).attr("data-icons"),
        data_text = $(this).attr("data-text");
    $(this).button({
        icons: btnInfo(data_priority, data_icons),
        text: (data_text == "false" ? false : true)
    }).addClass('ui-priority-' + data_priority).parent().removeClass("tdbLink")
});
})
</script>
<script type="text/javascript" src="ext/modules/shopping_cart/jquery-oscart.js?1100"></script>

 

 

2. This whole AJAX thing works only if the bm_shopping_cart.php is activated and used. What need to be changed so that the AJAX feature works only on the shopping_cart.php site without all the other stuff. No flying, no dragging, no shopping cart in the left or right column?

 

What? You want it Without all the bells and whistles, you mean?  (w00t) 

 

If you want to simply disable the bells (and the whistles) then just change this in jquery-oscart.js

	$('.buttonAction_oscart').click(function()

To this:

	$('.buttonAction_oscart2').click(function()
Link to comment
Share on other sites

@@Dr. Rolex

 

You did a great job on this one. Very complex code for me to understand but it sure works.

 

 

What? You want it Without all the bells and whistles, you mean?

 

:blush:  Yeah, sounds crazy right? I just wanted to have the ajax effect for the shopping_cart.php page and have the item qty and $$$ amount in the header area to change. Something like in the demo site of mine.

 

Demo Site

 

The Demo site uses your Rev3 version (stripped down to only the necessary codes to make it work) which reacts a bit slower when clicking on plus or minus. That is why i am currently working through your Rev4 version.

It took me 1 week to understand more or less how Rev3 js file works and now i will probably spend another few days learning how Rev4 works.

I am absolutely a noob with jquery and javascript or ajax stuff so i do by the trial and error method.

 

I tried your button sample above and it didn't work (for now) i will keep playing with that code and see what results i can get. Thanks.

 

I wish you a Happy New Year! :boom: :sparkles: :beers:

Link to comment
Share on other sites

Haha, osC claims that I have been more emotional than this community allows!

 


You have posted a message with more emoticons than this community allows. Please reduce the number of emoticons you've added to the message

 

 

 

@@Dr. Rolex

 

You did a great job on this one. Very complex code for me to understand but it sure works.

 

 

 

Well, thanks but good code should be simplex to understand, should it not?  :P 

 

 

 

 

:blush:  Yeah, sounds crazy right? I just wanted to have the ajax effect for the shopping_cart.php page and have the item qty and $$$ amount in the header area to change. Something like in the demo site of mine.

 

 

And where are you now? Did you get it to work the way you wanted it to or what´s not working?

 

 

 

Demo Site

 

The Demo site uses your Rev3 version (stripped down to only the necessary codes to make it work) which reacts a bit slower when clicking on plus or minus. That is why i am currently working through your Rev4 version.

It took me 1 week to understand more or less how Rev3 js file works and now i will probably spend another few days learning how Rev4 works.

I am absolutely a noob with jquery and javascript or ajax stuff so i do by the trial and error method.

 

This was the way I forced myself to learn jQuery and it worked out quite well. When you understand the basics then the manuals/docs are relatively easy to understand..

 

I can highly recommend that you use Sublime Text as your text editor. It has many great Add-Ons which will greatly help when programming. If you're on a mac then Dash is a really good way to instantly get the documentation for a function. Just go to the function and press Alt+H.

 

SublimeCodeIntel is another great Add-On to ST which will display all errors in your code directly in the text editor window. It makes ut much easier to find what's wrong.

 

---

 

The general recommendation are to avoid writing .click events, such as

	$('.buttonAction_oscart').click(function() {

And instead use

	$( "body" ).on( "click", ".buttonAction_oscart", function( event ) {

If you want it to react to multiple events (like I think you mentioned click and keyup) then just do this

	$( "body" ).on( "click keyup", ".buttonAction_oscart", function( event ) {

To get which kind of event triggered it, check the event object

    $( "body" ).on( "click keyup", ".buttonAction_oscart", function( event ) {
        console.log( event.type );
    });

 

I tried your button sample above and it didn't work (for now) i will keep playing with that code and see what results i can get. Thanks.

 

I wish you a Happy New Year! 

 

If you have jQuery-UI, then it should work..

But you're layout is a bit different so I guess you want another style. Just add a simple button with type="submit" and then style however you want it.

 

Add this to the <td> that has the -/+ product quantity on the shopping_cart.php page. Add the button after the first div:

<div class="input-group input-group-sm" style="width:150px;text-align:center">
    <input class="btn btn-default" type="submit" value="Submit" style="width:100%">
</div>

The entire <td> should look like this

<td style="border-bottom:solid 1px #999999;padding:10px 0px;width:300px;"><div class="input-group input-group-sm" style="width:150px;">
    <span class="input-group-btn">
        <button type="button" class="btn btn-default update-qty moins" rel="28" style="visibility: visible;">
            <span class="glyphicon glyphicon-minus"></span>
        </button>
    </span><input type="text" name="cart_quantity[]" class="form-control text-center qty-input" id="pl28" value="3"><input type="hidden" name="products_id[]" value="28"><span class="input-group-btn">
        <button type="button" class="btn btn-default update-qty plus" rel="28" style="visibility: visible;">
            <span class="glyphicon glyphicon-plus"></span>
        </button>
    </span>
</div>

<div class="input-group input-group-sm" style="width:150px;text-align:center">
    <input class="btn btn-default" type="submit" value="Submit" style="width:100%"></div>
</td>

Let me know if you need any help and I'll try walk you through it.

 

Happy New Year, Motherf-cker!  :lol:  :)  :mellow:  :blush:  :wacko:  :x  :thumbsup: 

Edited by Dr. Rolex
Link to comment
Share on other sites

A HAPPY NEW YEAR TO YOU TOO!

 

Well, thanks but good code should be simplex to understand, should it not?  :P 

 

 

don't get me wrong your documentation inside the js file is great it helps to see what does what. For "my" skill level it is still complex. ;)

 

As you can see in my demo site (version Rev3) it is more or less working. At first i thought that the shopping cart box needs to be activated for the ajax stuff to work but that is not necessary. I now know that having the total amount or better say id="boxcart-total" insicde the header area does not require any changes to the shopping cart box anymore. So i can use the  ajax function only in the shopping_cart.php page.

 

The current downsides are:

 

 - slow reaction on updating price and qty. (this is solved with your Rev4 version)
 - need to have total price in header area or the bm_shopping_cart.php box set to "true"
 - when shopping_cart.php page is empty and push F5 to reload the left column is not showing
 - can't enter qty directly inside the input field. if qty is directly entered and pushed enter the item gets removed from the cart.

 - The total has an id and not class so it can't be used multiple times.

 

The last thing i did before going into a daily drinking frenzy (till yesterday) was just implementing your Rev4 version into my local store.

And at first sight it seems to work but i can't get the qty and total working inside the header area.

The whole idea was to get rid of the update button so i don't like to add another for the input function. Maybe it can be hidden?

Anyway i have to run now need to go for a last drinking thing and that's it.

 

If i could fix all the downsides then i would say it works.

Edited by Tsimi
Link to comment
Share on other sites

Prologue

 

​I'm sure I had good intentions when I started this tutorial or whatever it was supposed to be. Half way through writing, anyway, I felt I just needed to end it but probably didn't know how (since I had forgot what started it).

 

I have, halfheartedly, tried to sanitate it  so that you can understand some of it, but I'm not in a condition anymore to keep "meddling" with it. Haha  :P 

 

Tomorrow will likely be a most unlikable day and if I were smart I would go to bed any minute. But that's unlikely, though.. Can't quit now, so much fun to do, StIll!  (w00t)  :D  :mellow:  :- 

 

Anyway, just ask if you need help on something, but you should probably ask about one problem at a time so we don't risk having these () situations again.

 

Enjoy your "tutorial" and try to stay sane while experiencing it's full glory!

 

Edit: I now realize that I've accidentally removed the sanitized version of this tutorial which simply gives me no other choice then to give you the almost uncut version.

Took me 2 fu-king hours cleaning that one up (since I have no way to see what characters that surrounds perhaps the current word I'm focusing on.. I now realize that this luckily isn't a permeant handicap because that would probably limit to do anything legal while moving without some kind of trained beast clearing my way in front of me.

 

Enjoy! //  Dr. R.

 

 

 

 

A HAPPY NEW YEAR TO YOU TOO!

 

 

don't get me wrong your documentation inside the js file is great it helps to see what does what. For "my" skill level it is still complex. ;)

 

As you can see in my demo site (version Rev3) it is more or less working. At first i thought that the shopping cart box needs to be activated for the ajax stuff to work but that is not necessary. I now know that having the total amount or better say id="boxcart-total" insicde the header area does not require any changes to the shopping cart box anymore. So i can use the  ajax function only in the shopping_cart.php page.

 

---

 

The last thing i did before going into a daily drinking frenzy (till yesterday) was just implementing your Rev4 version into my local store.

And at first sight it seems to work but i can't get the qty and total working inside the header area.

The whole idea was to get rid of the update button so i don't like to add another for the input function. Maybe it can be hidden?

Anyway i have to run now need to go for a last drinking thing and that's it.

 

If i could fix all the downsides then i would say it works.

 

Hmm.. Is it just my own filthy odor that's giving of that smell or do I sense a fellow workaholic?  :- 

 

 

 

The current downsides are:

 

 - slow reaction on updating price and qty. (this is solved with your Rev4 version)

 - need to have total price in header area or the bm_shopping_cart.php box set to "true"

 - when shopping_cart.php page is empty and push F5 to reload the left column is not showing

 - can't enter qty directly inside the input field. if qty is directly entered and pushed enter the item gets removed from the cart.

 - The total has an id and not class so it can't be used multiple times.

 

[i couldn't retrieve this part of the tutorial, sorry ]  :blink: 

// Selecting Element By ID (distinct for this is the use of the # char before the ID_Name)
$( "#body_content" )

// Okay, so say that you want some JS/jQuery code to run when the user e.g. clicks on an element
$( "body" ).on( "click", "#body_content", function( event ) {
    // This will display various information on the event itself and also about the attributes of the element you have bound this event listener to.

    // This is usually the easiest way to give the jQuery code the vital information it need to process e.g deleting a product from the basket, adding, subtracting to it's quanity or any other process where the code needs to know which specific item/detail you want it to do any work on.

    /* Example: If you want to make sure that the shopping_cart.php FORM with the new product quantites the user has entered will be POSTED when clicking on the bootstrap button I suggested, then add this html right under the div that has the (-), product quanity and the (+) buttons:

<div class="input-group input-group-sm" style="width:150px;text-align:center">
    <input class="submit_form_button btn btn-default" id="submit-form-button" type="button" style="width:100%">
</div>

    Notice that I added the submit_form_button class which can be used as element selector.
    Also take note that if you ever want one event listnerer to handle multiple elements, then just add a custom class to that element and then change the jQuery code which in this example would originally look like this ( "#[Element-ID]", always # for IDS )

    *_- Select Element by ID -_*
    $( "#submit-form-button" );

    *_- Bind Event listener to Element by ID -_*
    $( "body").on( "click", "#submit-form-button", function( event ) {});

    So to make it possible to bind the event listener to multiple elements we simply change the selector to a class name and we make sure all elements that should trigger this event has the chosen class name ( ".[Element-ID]", always . for Classes. Valid classnames can only use underscores (_) in their name, while IDs can have both underscores (_) and hyphens (-) ).

    Both the event and this objects inside the event listener will always relate to the element that was e.g. in this case, clicked on. So you can safely use the same event listener on multiple elements as long ass they are selected by class and not ID.22§§

    *_- Select Element(s) by Class -_*
    $( ".submit_form_button" )

    *_- Bind Event listener to Element(s) by Class -_*/

    $( "body").on( "click", ".submit_form_button", function( event ) {
        console.log( "Here's the information stored in the  $( this )  keyword when used inside this specific click event" + "\n\n" ); console.log( $( this ) );
        console.log( "Here's the information stored in the  this  keyword when used inside this specific click event" + "\n\n" ); console.log( this );
        console.log( "Here's the information stored in the  event  keyword when used inside this specific click event" + "\n\n" ); console.log( event );
    });

    /* GO Ahead and copy and paste the above 5 lines snippet to the console in you browsers console. Just make sure that you got some element with the selected class (submit_form_button) so you can try it out. Click on the element with the submit_form_button class and check your console what information each of the object has for you.

    Next thing you can try in your shopping_cart.php to further modify the clickable element, is to add a new property name which start with data-[some random name] and has the products_id as value. So e.g. add

    data-productID="' . $products[$i]['id'] . '"

    to your button which should work as the form submitter for changing the product quantitites "manually". Run the snippet that you used above again, click the elemnt and you should see that now you "magically" have the products_id to use in the jQuery event listener. This can of course be done with whatever value that PHP cab output on an element as a property value.

    The reason why you should use data-productID="100" instead of e.g. rel="100" is because it's a HTML5 thing specifically designed for this kind of use.


    So the complete jQuery code which will listen for clicks on all elements that has it's chosen selector on them and whos only job is to submit the form when clicked on should look like this*/

    $( "body").on( "click", ".submit_form_button", function( event ) {
        
        // Submit the Outer Form which encapsules this element
        // this.form.submit();

        // Submit the Outer Form which encapsules this element with AJAX (preventing all elements on the page from updating)

        $.ajax({
            type: 'POST',
            url: encodeURI($('form[name=cart_quantity]').attr('action')) + '&ajax=1',
            data: $('form[name=cart_quantity]').serialize(),
            success: function(data) {
                $("#content-body").html(data);
            },
            dataType: 'html'
        });

        $.ajax( {
            type: 'POST', // Type of Request (GET/POST)
            url: encodeURI($('form[name=cart_quantity]').attr('action')) + '&ajax=1', // Element to get the form url from.
            data: $('form[name=cart_quantity]').serialize(), // Data/Parameters send with the Request, this command will simply calculate and add all the currently set form information that's available form switches, checkboxes, textarea etc..
            dataType: 'html', // Expected response: html, json etc.
        } ).done( function( data, status, xhr ) {
            // Here you put the code that shoule PROCESS the returned data object from the request. This Request to shopping_cart.php should give you the new updated html for the shopping cart which you now want to replace the old cart.

            // So.. Select Element with ID content-body and replace it's content with what was returned to us in the data object. (now containing html)
            $( "#content-body" ).html( data );
        } );
    });


    // Remember that if you want a button to be solely functional with jQuery to set the button type="button" and not to "submit". While set to "button" then you can click all you want without risking any unwanted Page reloads or FORM submits.

    // Well, when you get this basic understanding on how you can combine PHP and jQuery so they can work together then I think all the "other stuff" will be easy to solve by googling whatever whistlers you want to blow.

    // E.g. changing the html for a specific element (like updating ORDER $$$ inside it) you can do this with very little effort

    /* Let's say that you have one or two elements with the class="current_order_total" added to them and that inside this tag you have the Order Total showed as a number with whatever weird decimal and thousands your selected currency uses. Let's say you own a very classy shop that only accept old Gold Rubles that simply is way too classy to be divided in decimals or thousands, it will simply always be an integer value (which hopefully can be rounded down.).

    // Notice to whoever managed to read this far: the author are now starting to have "difficulties" with focusing eyes, in fact, most of the expected brain functions are becoming more of a blur right now, so I think it's better to end this "Lesson" (or whatever the original intent was) before it turns ugly..

    /* I'll have another drink, I think, to cool the troubled mind and then write one of many possible solutions to get & calculate the new order total from the HTML and finally updating whatever elemets that you want to show the order totals in.

    // Okay, feeling better already (¡!¡☺☺☺¡!¡) //

    Like I said, there's hundreds of possible ways to accomplish this. One would be to put a e.g.

    <span id="latest_order_total" style="display:none"><?php echo $currencies->format($cart->show_total()); ?></span>

    Somewhere, perhaps preferably someplace inside the form on shopping_cart.php, so that it updates every time the user updates the cart.

    And then update the event listener to replace the order total, full event should look something like this if you're using this tehnique */



    $( "body").on( "click", ".submit_form_button", function( event ) {
        
        // Submit the Outer Form which encapsules this element
        // this.form.submit();

        // Submit the Outer Form which encapsules this element with AJAX (preventing all elements on the page from updating)

        $.ajax( {
            type: 'POST', // Type of Request (GET/POST)
            url: encodeURI($('form[name=cart_quantity]').attr('action')) + '&ajax=1', // Element to get the form url from.
            data: $('form[name=cart_quantity]').serialize(), // Data/Parameters send with the Request, this command will simply calculate and add all the currently set form information that's available form switches, checkboxes, textarea etc..
            dataType: 'html', // Expected response: html, json etc.
        } ).done( function( data, status, xhr ) {
            // Here you put the code that shoule PROCESS the returned data object from the request. This Request to shopping_cart.php should give you the new updated html for the shopping cart which you now want to replace the old cart.

            // So.. Select Element with ID content-body and replace it's content with what was returned to us in the data object. (now containing html)
            $( "#content-body" ).html( data );

            // All right Sweetheart, almost done now, two final code snípers to solve the riddle
            // Since the entire cart has been refreshed (but only that and nothing more) you now have the new order total in the <span> with ID latest_order_total that you placed in shopping_cart.php

            // 1. Get the order total string and save it to a variable
            var new_order_total = $( "#latest_order_total" ).html();

            // 2. All right, Sweetheart, as a last & final step, we want the string in new_order_total to be displayed in whatever element(s) you for some reason feel the urge to put it up for display.
            // So assuming you have class="current_order_total" on those element that you please, pretty please & if possible, would like to get the new flashy and very reasonable price updated attached on.

            //   Select Element(s) - and then - change their inner html to value in new_order_total
            $( ".current_order_total" ).html( new_order_total );

            /*** ¡¡¡ konke kwenziwa !!! ***/
        } );

});
Link to comment
Share on other sites

@@Dr. Rolex

 

WOW! (w00t) 

Thanks for that tutorial Doc! I will work through it step by step and see if i can clean out the last details to make this ajax function work for my purpose.

 

As said it is almost done, just the little details are the ones that need to be adjusted. I'll get to it asap. If I should have any troubles on the way i will ask here in the topic. Thanks again for the help! Very appreciated!  :thumbsup: 

Link to comment
Share on other sites

  • 3 years later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...