Multiple product add in cart on single button click - NopCommerce - javascript

I am currently working on a combo offer on NopCommerce. So I need to add multiple product to cart at a single click. The built in NopCommerce format is for adding single product into cart is
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + productId + '/1/1'
and
AjaxCart.addproducttocart_details('/addproducttocart/details/' +productId + '/1', '#product-details-form')
Both of them work fine for adding single product. But when I want to add multiple product then the it just add single product to the cart. Mention that I am sending a string with a coma separative value which is list of products and inside Javascript it is parsing as a single prodcut Id. However, it is adding only single product in the cart. Which Product Id is the the lowest that product is adding to the cart.
Here is my piece of javascript code
function addComboProductToCart(ids) {
var arrayOfStrings = ids.split(',');
for (var i = 0; i < arrayOfStrings.length; i++) {
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + arrayOfStrings[i] + '/1/1');
}
}
But it is not showing a single error too. So where is the problem?

At the first you need to change in public.ajaxcart.js as below as there is an ajax call on every Add to Cart we need to set it async:false for this you have to add a parameter called async for more clear take a look at below code
//add a parameter async
addproducttocart_catalog: function (urladd,async) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
$.ajax({
cache: false,
async:async,
url: urladd,
type: 'post',
success: this.success_process,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
},
Now i have modified your function by addding just a parameter false
function addComboProductToCart(ids) {
var arrayOfStrings = ids.split(',');
for (var i = 0; i < arrayOfStrings.length; i++) {
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + arrayOfStrings[i] + '/1/1',false);
}
}
To know what async:false is doing kindly find this answer as well for more clarification
Let me know if you need any further assistance.

Related

HTML DOM getElementById()-Node JS

I have this code that adds value to different parts of my html page based on the ID of that element,
the code works perfectly no issue but what I'm looking for is a better and efficient solution to replace all the getelementbyid feature, if there is one of course
which mean if there is another methode to reduce the size of the code below and change it with another one
my code is below :
$('#public-event').modal('show');
$.ajax({
type: 'GET',
dataType: 'json',
url: '/envoi/update/' + id,
})
.done(function (data) {
var html = ""
console.log(data);
for (let i = 0; i < data.length; i++) {
if (id === data[i].events._id) {
console.log(data[i].events.title)
document.getElementById("title").innerHTML = data[i].events.title;
document.getElementById("eventDateTime").innerHTML = `${data[i].events.eventDate} at ${data[i].events.targetReminder} | ${data[i].events.targetAmPM}`;
document.getElementById("createBy").innerHTML = data[i].events.author;
document.getElementById("dateCreation").innerHTML = data[i].events.author;
document.getElementById("description").innerHTML = data[i].events.caption;
document.getElementById("pubpriv").innerHTML = data[i].events.category;
document.getElementById("location").innerHTML = data[i].events.location;
$('#monImage').attr('src', 'img/sam.jpg');
$('#eventImage').attr('src', 'uploads/' + data[i].events.img);
document.getElementById("deleteButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("completeButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("CommentButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("CommentButtn").setAttribute('data-content', data[i].events.author);
document.getElementById("likeButton").setAttribute('data-id', data[i].events._id);
document.getElementById("likeButton").setAttribute('data-content', data[i].events.author);
document.getElementById("showComment").setAttribute('data-id', data[i].events._id);
document.getElementById("comment-number").innerHTML = data[i].events.comments.length +' Comments';
//to modify imges with dynamic
}
Thank you for any suggestion,
Best Regards,
Your code comprises of both native JS and jQuery, native being the more verbose. jQuery's own slogan is: "write less, do more" – so that's one note to take away from. But also, some elements require a particular type of formatting, so this shouts for explicit statements. You could also combine the repetitive values into one statement.
$('#title').text(data[i].events.title)
$('#eventDateTime').text(`${data[i].events.eventDate} at ${data[i].events.targetReminder} | ${data[i].events.targetAmPM}`)
$('#createBy, #dateCreation').text(data[i].events.author)
$('#description').text(data[i].events.caption)
$('#pubpriv').text(data[i].events.category)
$('#location').text(data[i].events.location)
$('#monImage').attr('src', 'img/sam.jpg')
$('#eventImage').attr('src', 'uploads/' + data[i].events.img)
$('#deleteButtn, #completeButtn, #CommentButtn, #likeButton, #showComment').attr('data-id', data[i].events._id)
$('#CommentButtn, #likeButton').attr('data-content', data[i].events.author)
$('#comment-number').text(`${data[i].events.comments.length} Comments`)
It's also noteworthy to make use of .text over .html if your values are genuinely just text and do not contain HTML. Otherwise, no harm in replacing with .html.

Ajax Table Result Is Not Calculating Sum Of Each Row's Price Column

screenshot of sale page
Hi all. I have a sale page and another page which shows result according to the ajax post. I don't know if you can see the image but let me explain shortly.
The left side of the page shows the list of chosen products according to the product list on the right side which works with ajax post. I click on the right side product buttons and AJAX results bring the product to the left side list with the product name, quantity and price of the product. Everything works fine till this step.
The problem is when i am choosing a product and it comes to the list of sale, i need to calculate the sum of this table's price column and show in another div-span out of this table. And i need to this live when i added a new product. And now it is showing the sum result of only first row in product list. Not calculating all.
This is the script of sum:
<script>
var $form = $('#satis_bitir'),
$sumDisplay = $('#ara_toplam');
$form.on('keyup', 'input', function ()
{
var $summands = $form.find('#toplam_tutar');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum.toFixed(2));
});
</script>
So how can i calculate the whole list's price columns and show in another div->span?
var updateCartAmount = function(){
var $form = $('#satis_bitir'),
$sumDisplay = $('#ara_toplam');
var $summands = $form.find('.toplam_tutar');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum.toFixed(2));
};
$.ajax({
type: 'GET',
url: 'your-url',
data: {},
success: function(){
updateCartAmount(); //call your updateCartAmount here when ajax done
}
});
Instead of using
#toplam_tutar
Try to use
.toplam_tutar
elements ids are unique means only the first div will be selected

Cannot replace class on the fly from localStorage in jQuery RSS Feed

I'm trying to fill RSS feed with add to fav utility using jQuery and HTML5 localStorage. What I'm trying to achieve is when a user clicks on glyphicon-star-empty available on title of post, it changes to glyphicon-star (which is done) but it should store the selected/favorited item in localStorage and on refresh instead of showing glyphicon-star-empty, it should fetch data from localStorage regarding which item is favorited and show glyphicon-star instead.
The problem i'm facing is in the last part. I can store fav items in localStorage but I don't seem to find the correct way to replace glyphicon-star-empty with glyphicon-star on the fly for favorited items when the page is refreshed.
the other problem is that when user clicks on glyphicon-bookmark (available near the heading -RSS) it should show all the favorited items and should also remove items from localStorage and current page on deselection (i.e clicking glyphicon-star)
here is the complete code fiddle.
and here is the jquery function i'm working on:
function blogRSS(url, container) {
var content = $('.data-content'); //console.log(content);
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
console.log(data.responseData.feed);
$.each(data.responseData.feed.entries, function(key, value) {
var thehtml = '<h4>' + value.title + '</h4>';
$("body").append(itemLayout);
$('.panel-heading').last().html(thehtml);
$('.data-content').last().html(value.content);
$('.data-title').last().next().slideToggle(0);
//console.log($('.panel-heading').last().html(value.title));
//console.log($('.panel-heading').closest('.data-title').text());
if(localStorage.favorite != null){
arr = JSON.parse(localStorage.favorite);
for(var i = 0; i < arr.length; i++){
// console.log($('.panel-heading').last().text() == arr[i].title);
if($('.panel-heading').text() == arr[i].title){
console.log('match');
$('.bkmark_icon').removeClass('glyphicon-star-empty');
$('.bkmark_icon').addClass('glyphicon-star');
//console.log('match');
}
}
}
}); $('.data-title').find('h4').addClass('panel-title');
Add a change like this inside the for loop,Basically you need to loop over each list element as well as for loop over the array to set it.
$( ".panel-heading" ).each( function( index, element ){
if($(this).text() == arr[i].title.trim()){
$(this).next().removeClass('glyphicon-star-empty');
$(this).next().addClass('glyphicon-star');
}
});
Here is a modified JSfiddle
https://jsfiddle.net/ehqefk6j/2/

How to check if a ResultSet of an AJAX call using JQuery has value

I am Using iQuery to make AJAX Calls to the server and return a set of values. The Values returned are dynamic. The Result count being dynamic I am not able to look the result set and assign values to HTML Elements to show in Web Page.
Kindly advice how I could look if there is a value in the result set and use the same in my system. The Maximum count in result set is 16 and i have manually assigned values in the Script.
Calling the AJAX Method in the document ready of my Web Page.
$(document).ready(function () {
CallAJAX('../Forms/Send.aspx/refreshDash', '', 'FillMethod', 'FillMethodE');
});
AJAX Call Definition
function CallAJAX(ServerMethod, Parameters, SuccessMethod, ErrorMethod) {
$.ajax({
type: "POST",
url: ServerMethod,
data: Parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
Error = xhr; Result.d.ResultSet[0].TRCOUNT
eval(ErrorMethod + "()");
},
success: function (msg) {
Result = msg;
var rr = SuccessMethod + "();";
eval(rr);
}
});
}
Using Two jQuery Functions to Show Details and prompt Message when error is Raised. Note Error Function is not Shown.
function FillMethod() {
if ($.isEmptyObject(Result.d.ResultSet)) {
}
else {
$('[id$=lblCode1]').html(Result.d.ResultSet[0].DASH_NAME);
$('[id$=lblNot1]').html(Result.d.ResultSet[0].TRCOUNT);
$('[id$=lblCode2]').html(Result.d.ResultSet[1].DASH_NAME);
$('[id$=lblNot2]').html(Result.d.ResultSet[1].TRCOUNT);
$('[id$=lblCode3]').html(Result.d.ResultSet[2].DASH_NAME);
$('[id$=lblNot3]').html(Result.d.ResultSet[2].TRCOUNT);
$('[id$=lblCode4]').html(Result.d.ResultSet[3].DASH_NAME);
$('[id$=lblNot4]').html(Result.d.ResultSet[3].TRCOUNT);
$('[id$=lblCode5]').html(Result.d.ResultSet[4].DASH_NAME);
$('[id$=lblNot5]').html(Result.d.ResultSet[4].TRCOUNT);
$('[id$=lblCode6]').html(Result.d.ResultSet[5].DASH_NAME);
$('[id$=lblNot6]').html(Result.d.ResultSet[5].TRCOUNT);
$('[id$=lblCode7]').html(Result.d.ResultSet[6].DASH_NAME);
$('[id$=lblNot7]').html(Result.d.ResultSet[6].TRCOUNT);
$('[id$=lblCode8]').html(Result.d.ResultSet[7].DASH_NAME);
$('[id$=lblNot8]').html(Result.d.ResultSet[7].TRCOUNT);
$('[id$=lblCode9]').html(Result.d.ResultSet[8].DASH_NAME);
$('[id$=lblNot9]').html(Result.d.ResultSet[8].TRCOUNT);
$('[id$=lblCode10]').html(Result.d.ResultSet[9].DASH_NAME);
$('[id$=lblNot10]').html(Result.d.ResultSet[9].TRCOUNT);
$('[id$=lblCode11]').html(Result.d.ResultSet[10].DASH_NAME);
$('[id$=lblNot11]').html(Result.d.ResultSet[10].TRCOUNT);
$('[id$=lblCode12]').html(Result.d.ResultSet[11].DASH_NAME);
$('[id$=lblNot12]').html(Result.d.ResultSet[11].TRCOUNT);
$('[id$=lblCode13]').html(Result.d.ResultSet[12].DASH_NAME);
$('[id$=lblNot13]').html(Result.d.ResultSet[12].TRCOUNT);
$('[id$=lblCode14]').html(Result.d.ResultSet[13].DASH_NAME);
$('[id$=lblNot14]').html(Result.d.ResultSet[13].TRCOUNT);
$('[id$=lblCode15]').html(Result.d.ResultSet[14].DASH_NAME);
$('[id$=lblNot15]').html(Result.d.ResultSet[14].TRCOUNT);
$('[id$=lblCode16]').html(Result.d.ResultSet[15].DASH_NAME);
$('[id$=lblNot16]').html(Result.d.ResultSet[15].TRCOUNT);
}
};
function FillMethodE() {
}
Issue is being raised in the FillMethod function when only Result.d.ResultSet[0].DASH_NAME has a valid value and the following indexes does not have any values.
NOTE: Results are returned in pairs, if DASH_NAME is available then TRCOUNT will also be available for the same index.
All I need to do is irrespective of the result count i need to display in the labels in order values from the result set dynamically. Here are are two sets of result sets which could be obtained.
I'm afraid it's still really, really unclear what the specific problem is (and the sample result sets you posted don't provide any clarity on why you can't simply loop over them), but I'm willing to take a guess...
Is the problem that you're trying to write a dynamic set of results to a static set of placeholders for the output?
If that's the case, don't make the placeholders static. Just keep an empty space where you want the results to show and when you have the results, write them to that part of the page. You don't need HTML elements in place already, you can create them dynamically. For example:
success: function (msg) {
// let's assume msg is an array of data
for(var i = 0; i < msg.lengh; i++) {
$('#output').append(
'<div>' + msg[i].DASH_NAME + ' - ' + msg[i].DASHSTATUS + '</div>'
);
}
}
So if your #output is just a div, the result would look like this:
<div id="output">
<div>SEND CONFIRMED - 1</div>
<div>RECV HO RESPONDED - 4</div>
<div>RECV HO PAID - 3</div>
<!-- etc... -->
</div>
How you define and style that markup is entirely up to you, of course. The point is that you can create the markup on the fly from your JavaScript code, so it can be created dynamically based on the results from the AJAX request.
Try this
if (Result.d.ResultSet.length > 0) {
for (i = 0; i < Result.d.ResultSet.length; i++) {
$('[id$=lblCode'+i+']').html(Result.d.ResultSet[i].DASH_NAME);
$('[id$=lblNot1'+i+']').html(Result.d.ResultSet[i].TRCOUNT);
}

How to load 2 lists based on 2 select boxes on change of first box

From the title, you can understand that this one is a bit complicated, but it really shouldn't be. I'm sure this is an easy fix, I just can't wrap my head around it.
I have select box A which populates select box B whose combined criteria populate list A and list B. When select box A changes, the appropriate info loads into select box B and the lists should also get populated. Currently the lists only get populated when select box B changes.
It's set up so that on page load the first box A/B combo's lists get loaded. I need to set it up so that when box A changes (and box B automatically changes) the lists get loaded for box A/B criteria.
What I believe is happening is that when I attempt to attach any sort of handler to box B (or box A really) it looks to the previously loaded info in box B instead of the newly loaded info from when box A changed. I need it to look at the new A/B combo.
I've tried all sorts of handlers, javascript, jQuery: .onChange, .load, .live, .focus, but I don't think anything will work unless it picks up the new value in box B instead of the old value. I tried all this in the document ready function in the javascript and also in the .jsp:
<span class="caption">Business Unit</span>
<select style="margin-bottom: 20px" onchange="loadRatingPlans()"
name="cde_bus_unit" id="cde_bus_unit">
<c:forEach items="${divisions}" var="division">
<option value="${division.cdeBusUnit}">${division.nmeBusUnit}
</option>
</c:forEach>
</select>
<span class="caption">Rating Plan</span>
<select style="margin-bottom: 20px" onchange="loadAvailableLimitInfo();
loadBURPLimitInfo()"
name="cde_rating_plan" id="cde_rating_plan">
<c:forEach items="${ratingPlans}" var="ratingPlan">
<option value="${ratingPlan.cdeRatingPlan}">${ratingPlan.nmeRatingPlan}
</option>
</c:forEach>
</select>
This successfully changes the LimitInfo (lists A and B) when box B is physically selected. How do I make it do the same when just list A changes? Please ask me if you have any questions!! Thanks!
Here is the code for the javascript:
//populate the Rating Plans box based on the Business Unit
function loadRatingPlans() {
var busUnit = $('select[name="cde_bus_unit"]').val();
$.ajax({
type : 'GET',
url : 'loadRatingPlans.do',
dataType : 'json',
data : {
busUnit : busUnit
},
success : function(data) {
console.log(data);
//get rid of old rating plans
$('[name=cde_rating_plan]').empty();
//load new rating plans
if (data != null) {
data.forEach(function(rp) {
$('<option>').text(rp.nmeRatingPlan).val(rp.cdeRatingPlan)
.appendTo('[name=cde_rating_plan]');
}); // end forEach
}// end if
} // end success
});// end ajax
}// end uploadRatingPlans
//load the available limits based on which are already assigned
function loadAvailableLimitInfo() {
var cdeBusUnit = $('#cde_bus_unit').val();
var cdeRatingPlan = $('#cde_rating_plan').val();
$.ajax({
type : 'GET',
url : 'loadAvailableLimitInfo.do',
dataType : 'json',
data : {
cdeBusUnit : cdeBusUnit,
cdeRatingPlan : cdeRatingPlan
},
success : function(data) {
console.log(data);
$('#limAvailable').empty();
var i;
for (i = 0; i < data.length; i++){
$('#limAvailable').append('<li class="limit-list" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAvailable').append('\n');
}
} // end success
});// end ajax
}// end loadDivisionInfo
//load the assigned limits
function loadBURPLimitInfo() {
var cdeBusUnit = $('#cde_bus_unit').val();
var cdeRatingPlan = $('#cde_rating_plan').val();
$.ajax({
type : 'GET',
url : 'loadBURPLimitInfo.do',
dataType : 'json',
data : {
cdeBusUnit : cdeBusUnit,
cdeRatingPlan : cdeRatingPlan
},
success : function(data) {
console.log(data);
$('#limAssigned').empty();
var i;
for (i = 0; i < data.length; i++){
if(data[i].indDefault = -1){
$('#limAssigned').append('<li class="limit-list,
assigned-li-default" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAssigned').append('\n');
}
else{
$('#limAssigned').append('<li class="limit-list" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAssigned').append('\n');
}
}
} // end success
});// end ajax
I worked it out. The answer is to create a method that will return the lists based on just the value of the first box. I go to the db and grab the value of the list for the second box and then return the lists based on the first value in that second list. I already had a method set up to do this for loading the lists based on the first set of values from the first and second boxes on the page load.

Categories

Resources