Last active
February 11, 2019 02:29
-
-
Save atikju/ebd2c1dc045c422b82fae5b0f38f471c to your computer and use it in GitHub Desktop.
Shopify - Add Multiple/Bundle Products to Cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var available_ids = []; //array of 'varaint_id - qty' | |
| //the following loop was for my case, you need to change the DOM selector for yours | |
| $('.devTable tbody tr').each(function(){ | |
| var thisQty = $(this).find('.devQty input').val(); | |
| if(thisQty > 0){ | |
| var xVarID = $(this).find('.devQty input').attr('data-value'); | |
| var toPushItem = xVarID+'-'+thisQty; | |
| available_ids.push(toPushItem); | |
| } | |
| }).promise().done( function(){ | |
| console.log("All done"); | |
| console.log(available_ids); | |
| }); //each qty ends | |
| for (var i = 0; i < available_ids.length; i++) { | |
| (function(i){ | |
| //we are applying setTimeout strategy to avoid fast looping what causes add to cart failure. | |
| setTimeout(function(){ | |
| console.log(available_ids[i]); | |
| //splitting the available_ids | |
| var formContents = available_ids[i].split('-'); | |
| //[0] returns the variant id to add to cart | |
| //[1] returns the quantity to add to cart | |
| var params = { | |
| type: 'POST', | |
| url: '/cart/add.js', | |
| data: 'quantity='+formContents[1]+'&id='+formContents[0], | |
| dataType: 'json', | |
| success: function(line_item) { | |
| console.log("success! - "+line_item.title); | |
| console.log('---'+i+'-----'); | |
| var iteration_length = i+1; | |
| //if iteration length is equal to the total length - it means that we have | |
| //reached the last item. Now we redirect to cart or may be show pop up | |
| if( iteration_length == available_ids.length ){ | |
| //redirect to cart or | |
| document.location.href = '/cart'; | |
| //do whatever | |
| } | |
| }, | |
| error: function() { | |
| console.log("fail"); | |
| } | |
| }; | |
| $.ajax(params); | |
| }, 1000 * i); | |
| //1000*i means this code fires 1 seconds after each iteration which makes sure addition of add to cart is | |
| //successful | |
| }(i)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment