I have a webshop, where user can order products only 1 piece/product. I need to check if that user already has same product in cart and if is, alert that and not add that product to cart again. If product is not in cart, add it to cart.
This is first what I tried, but it always adds product to cart even terms in If is true. Problem is cart.
$(".glyphicon-shopping-cart").on("click", function() {
$(this).css("color", "#29d646");
var BookID = $(this).parent().parent().prev().prev().prev().prev().prev().prev().text();
$.ajax({
type: 'GET',
url: '/api/selections/' + BookID,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
},
success: function(sel) {
//check if Book is in cart already
$.ajax({
type: 'GET',
url: '/api/carts',
dataType: 'json',
success: function(cart) {
if (cart.CompanyID == JSON.parse(localStorage.getItem('userName')) && cart.ISBN == sel.ISBN) {
alert('Product is already in cart');
} else {
var toCart = {
CompanyID: JSON.parse(localStorage.getItem('userName')),
Orderdate: getdate(),
ISBN: sel.ISBN,
BookName: sel.BookName,
Author: sel.Author,
Publisher: sel.Publisher,
Price: sel.Price,
Season: sel.Season,
IsInCart: true,
};
$.ajax({
type: 'post',
url: '/api/Carts',
data: toCart,
success: function() {
console.log('Added to cart ' + BookID);
location.reload();
},
error: function() {
alert('Virhe!');
}
});
}
}
});
}
});
});
This in another way I tried to do this, now IF -statement is working but still product is added to cart. What should I do?
//check if Book is in cart already
$.ajax({
type: 'GET',
url: '/api/carts',
dataType: 'json',
success: function(cart) {
$.each(cart, function(i, carts) {
if (carts.CompanyID == JSON.parse(localStorage.getItem('userName')) && carts.ISBN == sel.ISBN) {
alert('Product is already in cart');
}
})
var toCart = {
CompanyID: JSON.parse(localStorage.getItem('userName')),
Orderdate: getdate(),
ISBN: sel.ISBN,
BookName: sel.BookName,
Author: sel.Author,
Publisher: sel.Publisher,
Price: sel.Price,
Season: sel.Season,
IsInCart: true,
};
$.ajax({
type: 'post',
url: '/api/Carts',
data: toCart,
success: function() {
console.log('Added to cart ' + BookID);
location.reload();
},
error: function() {
alert('Virhe!');
}
});
}
});
}
I don't know if this is right approach to this, if someone has better solution, please let me know.
var present=false;
$.each(cart, function(i, carts) {
if (carts.CompanyID == JSON.parse(localStorage.getItem('userName')) &&
carts.ISBN == sel.ISBN) {
alert('Product is already in cart');
present=true;
}
})
if(present===false){
other ajax part
}
You can get out of the function immediately by adding return. It 'early exits' the function and will prevent the program to proceed in adding cart.
if (...) {
alert('Product is already in cart');
return;
}
Related
When the user likes a story on the card, users saves it with the "save" button. I do this as a savePost in my .js file. But if the user is not registered I am redirecting as "location.replace(APP_URL + "/login")".
I want to redirect to a modal on the homepage instead of /login. Is it possible for me to do this as a session or something?
function savePost(t) {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
$(this);
$.ajax({
url: APP_URL + "/save_favorite",
type: "POST",
dataType: "json",
data: {
item: t,
_token: $('meta[name="csrf-token"]').attr("content")
},
success: function(e) {
1 == e.bool ? $("#save-icon-" + t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-" + t).removeClass("icon-filled").addClass("text-muted")
},
error: function(e) {
location.replace(APP_URL + "/login")
}
})
}
Your current JS:
function savePost(t) {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
$(this);
$.ajax({
url: APP_URL + "/save_favorite",
type: "POST",
dataType: "json",
data: {
item: t,
_token: $('meta[name="csrf-token"]').attr("content")
},
success: function(e) {
1 == e.bool ? $("#save-icon-" + t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-" + t).removeClass("icon-filled").addClass("text-muted")
},
error: function(e) {
location.replace(APP_URL + "/targetPage?showModal=1")
}
})
}
At the end of your target page add:
#if(isset($_GET['showModal']) && $_GET['showModal'] == 1)
<script type='text/javascript'>
$(window).on('load', function() {
$('#your modal id').modal('show');
});
</script>
#endif
In your routes/web.php add this:
Route::get('/', function () {
if(Auth::guest()){
return view('target.page');
} else {
return redirect('/somewhere');
}
});
I'm trying to get success event but it works only for error: event Don't know what is error.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://localhost/Register/intl-tel-input-master/next.php",
data: {
arguments: [fname, lname, email, Numb, pass, confirm]
},
dataType: 'JSON',
complete: function(data) {
if (('error' in data)) {
this_form.find('.error-message').slideDown();
} else {
alert(data);
this_form.find('.sent-message').slideDown();
}
}
});
// return false;
});
Try to check response using done/fail:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://localhost/Register/intl-tel-input-master/next.php",
data: {
arguments: [fname, lname, email, Numb, pass, confirm]
},
dataType: 'JSON',
})
.done((res) => {
console.log(res)
})
.fail((res) => {
console.log(res)
})
});
I want to call a function to count the items in the cart. I put that function in AJAX when I click the add to cart button. The result of add to cart process is 'success' but count_item() doesn't return anything, or it only an empty page. What's wrong with my code?
$(document).ready(function() {
/* add product to cart */
$(document).on('click', '.btn-addto-cart', function() {
var id = $(this).attr('id');
var productname = $('#name' + id).val();
var productprice = $('#price' + id).val();
var quantity = $('#quantity' + id).val();
if (quantity > 0) {
$.ajax({
url: "{{ url('shop/addtocart') }}",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
delay: 5000,
data: {
productid: id,
name: productname,
price: productprice,
quantity: quantity,
},
success: function(data) {
count_item();
swal("Success", "Product success added to cart", "success");
}
});
} else {
swal("Warning", "Minimum add to cart must be 1", "error");
}
});
/* to get total item in cart */
function count_item() {
$.ajax({
url: "{{ url('shop/counttotalitem') }}",
method: "GET",
header: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
delay: 5000,
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
});
I add the event to fullcalendar somewhere in far future. after that I refetchEvents() to have it displayed. Unfortunately fullcalendar goes back to current day, week or month and do not stay in edited day, week or month.
Is there any way to prevent it? Thanks.
I am not sure if that will be sufficient part of code:
if (deleteEvent){
$.ajax({
type: 'POST',
url: 'reservation-delete.php',
data: {
id: eventId
},
success: function (feedbackJsonString){
const feedbackJson = JSON.parse(feedbackJsonString);
calendar.refetchEvents();
}
});
} else {
if (eventId == 0) {
$.ajax({
type: 'POST',
url: 'reservation-add.php',
data: {
id: eventId,
start: eventStartDateTime,
end: eventEndDateTime,
title: eventTitle
},
success: function (feedbackJsonString){
const feedbackJson = JSON.parse(feedbackJsonString);
calendar.refetchEvents();
}
});
} else {
$.ajax({
type: 'POST',
url: 'reservation-edit.php',
data: {
id: eventId,
start: eventStartDateTime,
end: eventEndDateTime,
title: eventTitle
},
success: function (feedbackJsonString){
const feedbackJson = JSON.parse(feedbackJsonString);
calendar.refetchEvents();
}
});
}
}
If some specific part of code would be needed pls let me know.
I have an AJAX registration form:
var id = null;
$.ajax({
type: 'POST',
url: requestUrl,
data: $(".defaultRequest").serialize(),
dataType: 'json',
success: function(data) {
if(data.response){
$('div.errormsg').remove();
if(data.step){
openStep(data.step);
}else{
openStep('next');
}
}else{
$('div.errormsg').remove();
$('<div class="errormsg">'+data.message+"</div>").insertBefore(form);
}
}
});
When a user is successful registered, I want to show him his unique ID, but it stays NULL. How can I solve it?
<script type="text/javascript">
$('#linkkk').text('Your id is: '+id+'');
</script>
you need to set id first in success callback.
$.ajax({
type: 'POST',
url: requestUrl,
data: $(".defaultRequest").serialize(),
dataType: 'json',
success: function(data) {
if(data.response){
$('div.errormsg').remove();
if (data.step) {
openStep(data.step);
} else {
openStep('next');
}
$('#linkkk').text('Your id is: ' + data.id);
} else {
$('div.errormsg').remove();
$('<div class="errormsg">'+data.message+"</div>").insertBefore(form);
}
}
});