When I add a product to the cart I am using the code below:
addproduct(itemId) {
this.showLoading = true
this.$http.post('/shampoo', {'item': itemId}).then((response) => {
swal({
title: "Success!",
text: "Product added to your basket!",
type: "success",
timer: 1500,
showConfirmButton: false
})
this.showLoading = false
}, (response) => {
this.showLoading = false
})
I created a popup form which for no product was at the cart, once they click on the add to cart button it popups, once the product was their at the cart, if any one need to add another product it again showing popup. I don't want the popup if product was at the cart
here is the code for popup form
show() {
this.showLoading = true;
$(".loading").css('display', 'block');
$('#products').modal("hide");
//
let code = $('input[name=code]').val();
if(code) {
this.$http.post('/codee', { code: code}).then((response) => {
// $('#basic-form').submit();
}, (response) => {
swal({
title: "Error!",
text: "Sorry this Code is invalid!",
type: "error",
timer: 2500,
showConfirmButton: false
})
$(".loading").css('display', 'none');
this.showLoading = false
$('input[name=code]').val('')
})
When you click add to cart, at the server side, you need to check if the item id is in the cart and return a flag to either indicate the item is in the cat or not. I assume this code is responsible for the pop up.
swal({
title: "Error!",
text: "Sorry this Code is invalid!",
type: "error",
timer: 2500,
showConfirmButton: false
})
You need to check for the returned value from the server, if it returns a flag indicating that the item already exist, just return false; that will block the pop up code from being reached. or you could wrap the pop code in an if statement. e.g
if(response.flag === 1){
return false;
// your pop up code goes here
}
or
if(response.flag === 0){
// your pop up code goes here
}
// flag can assume 0 => Added but does not exist, 1=> added but already
// exist. ect
// while the actual data will be stored in response.data
But I am wondering of the reason you are implementing this. If a user clicks add to cart, you are supposed to increment the number of that same item if already exist in the cart
Related
I am trying to create a sweetAlert2 function where I want to fire a loading screen. And during the loading screen, I want to execute some functions, which can take some time. Afterward I want to display a fire success or error, depending on what the return will be. I tried several methods:
Swal.fire({
title: 'Auto close alert!',
html: 'In progress',
timerProgressBar: true,
didOpen: () => {
try {
Swal.showLoading();
call other functions..
if success show
Swal.fire({
icon: 'success',
title: 'Success...',
html: message
});
or else fire error
catch(err){
etc.
}
}
)};
Now when I execute the function it waits a few seconds (executing functions) and then it shows the success or error fire, but it doesn't show the in-progress loading dialog first. Any idea how to get this?
Fixed it by using setTimouts and promises:
//Start
Swal.fire({
title: 'In progress',
html: 'Please wait while your action is being carried out.',
timerProgressBar: true,
didOpen: () => {
//here it will open the in progress box
Swal.showLoading();
//setTimeout with 1000 or more ms is needed in order to show the inprogress box
setTimeout(async () => {
let currentRecID = currentRecord.get().id;
//load complete record
currentRec = record.load({
type: record.Type.OPPORTUNITY,
id: currentRecID,
isDynamic: true
});
const promiseVar = () =>
new Promise((resolve, reject) => {
resolve(canCreateORD(currentRec));
});
canORDbeCreated = await promiseVar();
//Automatically close popup so it continues with willClose
Swal.close();
}, 1000);
},
willClose: () => {
//Show success / error box with Swal.fire
So I have this Sweetalert2 function and it works great. Except it runs as soon as the page loads which is not what I want.
What I want is when I click on an element. I want it to be executed!
Also, I noticed that if the alert runs for the first time. It doesn't run when I click it because it ran on the first time
HTML
<i class="fas fa-search navigation__search-cart--icon"></i>
JS (SweetAlert file. From here I'm exporting the function that always gets called.)
export default sweetAlert = Swal.fire({
title: "Search...",
input: "text",
inputAttributes: {
autocapitalize: "off"
},
showCancelButton: true,
confirmButtonText: "Search",
showLoaderOnConfirm: true,
preConfirm: async val => {
try {
const response = await fetch(`//api.github.com/users/${val}`);
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
} catch (err) {
Swal.showValidationMessage(`Request failed: ${err}`);
}
},
allowOutsideClick: () => !Swal.isLoading()
}).then(result => {
if (result.value) {
Swal.fire({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
});
}
});
JS (Where the actual click happens)
import sweetAlert from "./sweetAlert";
const search = document.querySelector(
".fas.fa-search.navigation__search-cart--icon"
);
search.addEventListener("click", sweetAlert);
What should I do to stop the function from running on page load? And how can I make it run whenever I click on the element?
I've got a kind of projects management system, and I use a sweetalert popup as a settings menu for each project, and I want to fire a toast when a setting is changed, but that causes the menu to close. Is there a way to make this work without using another library just for toasts?
Here's the code I'm trying to run for the sweetalert menu
var id = 65352;
Swal.fire({
title: 'settings for project '+id,
html:
"<p>some setting</p>"+
"<input class='toggle' id='setting' data-docid='"+id+"' type='checkbox' checked>",
showCancelButton: true,
showConfirmButton: false,
cancelButtonText: 'close',
onBeforeOpen: () => {
const setting = $("#setting[data-docid="+id+"]");
$(setting).on("change",function(){
console.log($(this).attr("checked"));
if($(this).attr("checked") == "checked"){
$checked = 1;
}else{
$checked = 0;
}
$.parameters = {
id: id,
checked: $checked,
type: "accept"
}
//using an api to communicate between client and server
result = "TRUE"
if(result.indexOf("TRUE") > -1){
const Toast = Swal.mixin({ //when firing the toast, the first window closes automatically
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
Toast.fire({
type: 'success',
title: 'changed the thingy successfully'
})
}else{
const Toast = Swal.mixin({ //when firing the toast, the first window closes automatically
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
Toast.fire({
type: 'error',
title: 'cant change the thingy'
})
}
});
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8.11.5/dist/sweetalert2.all.min.js"></script>
Unfortunately, reading this thread it seems that it's not possible because a toast IS an modal in a way ...
But the last comment pointed out it could be possible modifying the code of Swal2 ;)
I am working on a shopping website and want to check if the item is present in the cart. If it exists, alert it's already in the cart and return false. If it doesn't exist add it to the cart.
I tried it like below, the code is working fine but the alert is looping.
$("#showBtn").focus();
msgBoxImagePath = "http://www.ournestonline.com/assets/images/";
function showMsgBox() {
simpleCart.bind('beforeAdd', function (item) {
if (simpleCart.has(item)) {
alert("Already in the Cart");
$.msgBox({
title: "Shopping Cart",
content: "Already in cart",
type: "alert"
});
return false;
} else {
$.msgBox({
title: "Shopping Cart",
content: "Great Selection Your Item is Added to Cart Happy Shopping",
type: "alert"
});
}
});
}
try adding
return false;
after the closing tag of else.
Im using jTable to display CDs info and a child table to show reviews of that CD. I want to be able to only show the edit\delete buttons on the rows for the user that is logged in. I have been trying to follow the suggestions made on: https://github.com/hikalkan/jtable/issues/113
https://github.com/hikalkan/jtable/issues/893
https://github.com/hikalkan/jtable/issues/620
Can honestly say im not having much luck with any of these examples. We had been told to include some jquery in our assignment so I chose to go with using it for my table data. Im wishing now id just done something very basic!
Working jTable without condition:
display: function (reviewData) {
//Create an image that will be used to open child table
var $img = $('<img class="child-opener-image" src="/Content/images/Misc/list_metro.png" title="List Reviews" />');
//Open child table when user clicks the image
$img.click(function () {
$('#ReviewTableContainer').jtable('openChildTable',
$img.closest('tr'),
{
title: "Your reviews on this album",
actions: {
listAction: 'childReviewActions.php?action=list&ID=' + reviewData.record.CDID,
deleteAction: 'childReviewActions.php?action=delete&ID=' + reviewData.record.CDID,
updateAction: 'childReviewActions.php?action=update&ID=' + reviewData.record.CDID
},
fields: {
userID: {
key: true,
create: false,
edit: false,
list: false
},
userName: {
title: 'User',
edit: false,
width: '20%'
},
reviewDate: {
title: 'Review date',
width: '20%',
type: 'date',
edit: false,
displayFormat: 'dd-mm-yy'
},
reviewText: {
title: 'Review',
type: 'textarea',
width: '40%'
}
},
Issue 620 attempt:
actions: {
listAction: 'childReviewActions.php?action=list&ID=' + reviewData.record.CDID,
#if (reviewData.record.userID == <?php echo mysql_real_escape_string($_SESSION['ID']);?>)
{
deleteAction: 'childReviewActions.php?action=delete&ID=' + reviewData.record.CDID,
updateAction: 'childReviewActions.php?action=update&ID=' + reviewData.record.CDID
}
},
This way gives me compile error: invalid property id on the IF statement.
If I take out the # in the if statement I get: missing : after property id.
Issue 113 & 893 attempt:
actions: {
listAction: {
url:'http://localhost/childReviewActions.php?action=list&ID=' + reviewData.record.CDID
//updateAction: {
//url:'childReviewActions.php?action=update&ID=' + reviewData.record.CDID,
//enabled: function (data) {
//return data.record.userID = <?php echo mysql_real_escape_string($_SESSION['ID']);?>;
//}
//}
},
On this I couldnt even get it to list the contents of the child table. It keeps coming back with 404 not found error: The requested url /[object object] was not found on this server. Has anyone any ideas how to get these examples working on have a different example of how to get the table to enable\enable the edit, update buttons? This is all new to me so I apologise now
rowInserted: function (event, data) {
//After child row loads. Check if the review belongs to the member logged in. If not remove the edit/delete buttons
if (data.record.userID != $user) {
data.row.find('.jtable-edit-command-button').hide();
data.row.find('.jtable-delete-command-button').hide();
}
else{
//If a review record does belong to the user set variable to true so the add new review link can be hidden after all records have been loaded
$memberReviewExists = true;
//Also needed here for when a new record is inserted
$(".jtable-add-record").hide();
}
},
recordsLoaded: function (event, data) {
if (typeof $memberReviewExists != 'undefined' && $memberReviewExists == true){
$(".jtable-add-record").hide();
$memberReviewExists = null;
}
else {
//No review currently exists for this user so show the Add review link $(".jtable-add-record").show();
}
},
recordDeleted: function (event, data) {
//User has deleted their review. Re-show the add new review link
$(".jtable-add-record").show();
}
The following worked for me. It hides the edit/delete button on rows where the current user is not the authorized user. Note: I added a column for authorizedUser in the mysql table and use that to know if the user is allowed or not.
rowInserted: function(event, data){
var $currentUser='<?php echo $_SESSION['email']?>';
if (data.record.authorizedUser != $currentUser) {
data.row.find('.jtable-edit-command-button').hide();
data.row.find('.jtable-delete-command-button').hide();
}
},
#Toni Your code contains asp.net code too. # is ASP.NET Directive.