📜 ⬆️ ⬇️

JQuery online shopping cart module

When developing online stores, I often had to use javascript (and more specifically its jQuery framework) to do some things from project to project. For example, adding products to the cart, updating information about the number of products and the total amount on the page, removing the goods from the cart one by one, changing their quantity and completely clearing all items from the cart. And all this, of course, without reloading the page.
And I came to the conclusion that you need to write code so that later it could easily be used in the following projects.

So, we are writing a module for working with the basket of an online store using jQuery.
I will make a reservation that I will publish only the javascript code, I will not touch the server part, I will also indicate what data the client will exchange with the server.

We determine the methods:
(function($) { $.Cart = { init : function(settings){ //   }, add : function(context){ //         1. }, get : function(){ //           }, count : function(context) { //           }, del : function(context) { //      }, clear : function() { //    }, showMessage : function(message) { //      } } })(jQuery); 


Initialization:
What do we need to do in the initialization?
It is necessary to process the settings passed to the init method, properly process (combine with the default settings) and apply them, and also hang the corresponding event handlers specified in the settings.
We are determined with the default settings.
 var defaults = { content : '.content', //       count : '.prod span font', //   .prod       summ : '.summ span font', //   .prod   add : '.tocart', //  ,          addattr : 'name', //  ,  ID  counta : '.carts .actions .count input', //         countattr : 'name', //  ,  ID  countvattr : 'value', //  ,    del : '.carts .actions .delete input', //  ,     1       delattr : 'name', //  ,  ID  clear : '.cartclear', //  ,        topcart : '.topcart', //      urladd : '/cart/add/', // url     urlget : '/cart/get/', // url          urlcart : '/cart/', // url    urlcount : '/cart/count/', // url      urlclear : '/cart/clear/', // url    urldel : '/cart/del/', // url       type_message : 'flash', //        time_message : 3000, //    interval : 10000 //  ,                }; 

We mix the parameters specified during initialization with the default parameters and apply them.
 $.extend(defaults, settings); this.settings = defaults; 

We update the block with information about the number of products in the basket and the total amount, hang event handlers on the specified elements and return the object's essence (it may be useful).
 this.get(); //   setInterval(function(){ $.Cart.get(); //        }, this.settings.interval); $(this.settings.add).click(function(){ $.Cart.add(this); //         settings.add,       }); $(this.settings.counta).live('blur', function(){ $.Cart.count(this); //    ,       ,     }); $(this.settings.del).live('click', function(){ $.Cart.del(this); //        "" }); $(this.settings.clear).live('click', function(){ $.Cart.clear(); //   }); return this; 


Adding one item to the cart in the amount of 1pc.
The add method, receives the context parameter (the element on which the click was made) and sends data to the server.
 $.ajax({ url : $.Cart.settings.urladd, //    type : 'post', //  dataType: 'json', //  ,   data : {id : $(context).attr($.Cart.settings.addattr)}, // ,   (id  ) success : function(data){ //    if (data.count && data.summ || data.count===0 && data.summ===0) { //           ,    $($.Cart.settings.count).html(data.count); //      $($.Cart.settings.summ).html(data.summ); //      if (data.count>0) //     ,  $($.Cart.settings.topcart).find('a').attr('href', $.Cart.settings.urlcart); //      else //    $($.Cart.settings.topcart).find('a').attr('href', 'javascript:void(0);'); //    $.Cart.showMessage('<p>'+data.message+'</p>'+$($.Cart.settings.topcart).html()); //   } }); 

')
Getting information about the number of products in the cart and the total amount, updating the block (get method).
It differs from the get method from the add to the url to which the data is sent and in the parameters (the get method does not pass parameters).
 $.ajax({ url : $.Cart.settings.urlget, type : 'post', dataType: 'json', data : {}, success : function(data){ if (data.count && data.summ || data.count===0 && data.summ===0) { $($.Cart.settings.count).html(data.count); $($.Cart.settings.summ).html(data.summ); if (data.count>0) $($.Cart.settings.topcart).find('a').attr('href', $.Cart.settings.urlcart); else $($.Cart.settings.topcart).find('a').attr('href', 'javascript:void(0);'); } }); 


I think in order to reuse the code, you can add some updateCart method to which the url and vars (parameters) will be passed.
 $.ajax({ url : data.url, type : 'post', dataType: 'json', data : data.vars, success : function(data){ if (data.count && data.summ || data.count===0 && data.summ===0) { $($.Cart.settings.count).html(data.count); $($.Cart.settings.summ).html(data.summ); if (data.count>0) $($.Cart.settings.topcart).find('a').attr('href', $.Cart.settings.urlcart); else $($.Cart.settings.topcart).find('a').attr('href', 'javascript:void(0);'); $.Cart.showMessage('<p>'+data.message+'</p>'+$($.Cart.settings.topcart).html()); } }, error : function(err) { if (err.status!==200) console.log(err.status+' '+err.statusText); } }); 


In turn, the add method will change to this.
 $.Cart.updateCart({ url : $.Cart.settings.urladd, data : {id : $(context).attr($.Cart.settings.addattr)} }); 


Get method
 $.Cart.updateCart({ url : $.Cart.settings.urlget, data : {} }); 


The change in the number of goods of the same name with the loss of the focus of the field corresponding to this name.
 count : function(context) { //   count   context ( -   ) $.post($.Cart.settings.urlcount, { //     url   id : $(context).attr($.Cart.settings.countattr), // ID   count : $(context).attr($.Cart.settings.countvattr) //     }, function(data){ //   (text/html) $($.Cart.settings.content).html(data); //     $.Cart.get(); //       }); }, 


Remove name.
 del : function(context) { //   del   context ( -       ) $.post($.Cart.settings.urldel, { //   id : $(context).attr($.Cart.settings.delattr) // ID  }, function(data){ //   (text/html) $($.Cart.settings.content).html(data); //     $.Cart.get(); //       }); }, 


Empty basket.
 clear : function() { $.post($.Cart.settings.urlclear, {}, function(data){ $($.Cart.settings.content).html(data); //   data    ,    $.Cart.get(); //     ,       }); }, 


Message about adding goods to the cart (depending on the type of alert or flash).
 showMessage : function(message) { //    if ($.Cart.settings.type_message==='alert') { //  alert alert(message); //   return; } else if ($.Cart.settings.type_message==='flash') { //  flash if ($('.flashmessage').length===0) //        ,  $('<div />').addClass('flashmessage').html(message).hide().appendTo('body').fadeIn(); //  ,    ,      </body>,    else //   $('.flashmessage').html(message); //      if (typeof($.Cart.message_time)==='number') //          clearTimeout($.Cart.message_time); //   $.Cart.message_time = setTimeout(function(){ //    $('.flashmessage').fadeOut(function(){ //       $(this).remove(); //      }); }, $.Cart.settings.time_message); //    } } 


Now it's all unite.
See this link for an example of a module.
and here you can download it as an archive.

The module will be added and corrected.

Thanks for attention. Waiting for critics, questions and comments.
There is a desire to modify it to a certain API working with online stores.

Source: https://habr.com/ru/post/141874/


All Articles