Creating an if in a js function - javascript

This is a code that filter all order history the user have but a want to create an if to just filter only the orders that I bought online (I have a variable that is 1 if is in the store and 2 if is online). How to i do the if?
filterOrderHistory: function() {
$(".historyorder-state").on('click', function(){
$('#filterOptions').show();
});
$('#filterOptions li').on('click', function() {
var text = $(this).text();
$('.tbl-shopping-history').html('<div class="form-spinner"><i class="fa fa-spinner fa-spin"></i></div>');
$.ajax({
method: "GET",
data: { state: $(this).attr('class').toUpperCase() },
dataType: "html",
url: '/impuls/store/components/order-history-table.jspf'
})
.done(function(data) {
$('.tbl-shopping-history').html(data);
$('.historyorder-state').html(text+'<i class="fa fa-caret-down"></i>');
$('#filterOptions').hide();
});
});
}
};

Related

Ajax call to change icons

I created below button
<button id="wishbtn" data-slug='{{ list.slug }}'><i class="far fa-heart"></i></button>
which calls an Ajax call.
$(document).on('click', '#wishbtn', function (e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function () {
alert('added to wishlist');
}
})
});
How do I change the class of i tag to fas fa-heart once the button is clicked. I tried using this keyword in success function to change its class $(this).classList.replace('far', 'fas') but it didn't work. I tried using e.target.getElementsByTagName('i')[0].classList.replace('far', 'fas') and again no hope.
Can you help me please, thank you.
$(document).on('click', '#wishbtn', function(e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function() {
let li = el.find('li')
li.removeClass('far')
li.addClass('fas')
}
})
});

Delete data by ajax in laravel

I'm trying to delete items by ajax, so far i can get each item id but somehow when i click on delete button it just getting first item id.
code
controller
public function delqtydisc(Request $request,$id)
{
$dele = QtyDiscount::find($id)->delete();
return response()->json($dele);
}
route
Route::post('/delqtydisc/{id}', 'QtyDiscountController#delqtydisc')->name('delqtydisc');
script
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
//this adds new items to database (no issue here)
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>');
var $tr = $('<tr/>');
$tr.append($('<td/>').html(data.min));
$tr.append($('<td/>').html(data.max));
$tr.append($('<td/>').html(data.amount));
// This adds delete button to my table
$tr.append($('<td/>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
// From this part delete function adds
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $('.qtyitemid').data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});
// end of delete fuction
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: I commented each part of my JavaScript code that I thought should
bring your attention
// This adds delete button to my table and // From this part delete function adds
Error
when I hit delete button I get 3 results (if i have 3 inputs) in my network, first one return true the other 2 return
"message": "Call to a member function delete() on null",
Any idea?
Update
with code below my problem is solved some how, the only issue is remained is that i still get my row id's multiple. e.g. when i delete id=1 network show it one time but when after that i delete id=2 network shows two times id=2
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>').fadeIn().delay(4000).fadeOut();
var $tr = $("<tr id='" + data.id + "'>");
$tr.append($('<td>').html(data.min));
$tr.append($('<td>').html(data.max));
$tr.append($('<td>').html(data.amount));
$tr.append($('<td>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
//delete item
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>').fadeIn().delay(3000).fadeOut();
$('table tr#'+QtyitemID+'').remove();
}
});
});
//
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: basically most of my problem is solved i'm just looking for answer
to avoid this multiple id in network.
The error occurred in your qtyitemid on click event. Specifically this line: var QtyitemID = $('.qtyitemid').data('id');
This JS code will always return the data of the first qtyitemid class. You must use the keyword this to determine what element is clicked. This code hopefully fix the problem:
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});

How to apply changes to the current class in jQuery?

I've read similar questions and tried different methods, but nothing seems to work. I have a Liking system. A heart image which switches between liked (filled heart icon) and unliked (Plain bordered heart icon).
The problem is, when I click on the like/heart button, all the other records' heart icon turns to liked state. The same goes with the like count. When I like a post, all the post's like count becomes the same.
Also, I'm running an AJAX request to get the likes count. When I try to output the likes and increment/decrement if they like/unlike, the output is weird. It goes to -1 or 01 etc.
This is my main.blade.php :
<span class="activityLikes">
<input type="hidden" class="activityIdHidden" value="{{ $activity->activity_id }}">
<a class="likeBtn">
#if(Auth::user()->hasLikedActivity($activity))
<img class="likeImg likeTrue" src="IMG/icons/likeTrue.png" alt="likes">
#else
<img class="likeImg likeFalse" src="IMG/icons/like.png" alt="likes">
#endif
</a><span class="likesCount">{{ $activity->likes->count() }}</span>
</span>
This is my main.js file :
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
$('.likeImg').attr('src', 'IMG/icons/like.png');
$('.likesCount').text(likeCount - 1);
} else if(data == "liked"){
$('.likeImg').attr('src', 'IMG/icons/likeTrue.png');
$('.likesCount').text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
It is because you update every image that has the .likeImg class on the success event.
Can you try the following code ?
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
// element to update is `this` (the element that had been clicked)
var elementToUpdate = $(this).children('img');
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
elementToUpdate.attr('src', 'IMG/icons/like.png');
elementToUpdate.text(likeCount - 1);
} else if(data == "liked"){
elementToUpdate.attr('src', 'IMG/icons/likeTrue.png');
elementToUpdate.text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
You should chain your Ajax calls, and get the count after updating the "like" status, like this:
function errHandler(e) {
console.log(JSON.stringify("Exception: " + e));
}
$('.likeBtn').on('click', function(e){
var activityId = +$(this).siblings(".activityIdHidden").val(),
$img = $("img", this),
$likes = $(this).siblings(".likesCount");
e.preventDefault();
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
error: errHandler
}).then(function(data){
$img.attr('src', data === "deleted" ? 'IMG/icons/like.png' : 'IMG/icons/likeTrue.png');
return $.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
error: errHandler
});
}).then(function(data){
$likes.text(data);
});
});

Jquery replaceWith in a Foreach loop

When I execute the below code all the img with the id of imgg will be replaced because they are in a foreach loop, but I want to apply that to the clicked one only. Can any one help?
Html:
<button type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" style="width:100px;height:30px">
<p id="imgg">Add to Cart</p>
</button>
JS:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(imgg).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(imgg).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Thanks everyone i found the solution But you da real MVP, here it is
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var imgid = $(this).find("#imgg");
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success: function(data) {
$(imgid).replaceWith('<img id=imgg src=img/ajax.gif> ');
var thisForm = this;
setTimeout(function() {
$(imgg).replaceWith(' <p id=imgg>Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error : function(data)
{
alert("You must Login First");
}
});
return false;
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
Instead of using the $(imgg) use $(this), and you also missed the quotations when you where giving the id of iamge when you where using .replaceWith:
success: function(data) {
$(this).replaceWith('<img id="imgg" src="img/ajax.gif>" ');
var thisForm = this;
setTimeout(function() {
$(thisForm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
Reason?
Simple. The this object doesn't change. It is the owner of the function. See more about why here: Jquery - When to use "this" and when to use "$(this)"?
EDIT2
Now i have to put that in the upper level so this:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var vm = this //Upper Level
var data = $(this).find("#post_id").val();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(vm).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(vm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Please refer here about this particular problem:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

filtration and pagination using ajax call in jquery

I want to do filtration and pagination in one script. I have done filtration and pagination separately. But when I combine this two code snippet pagination is not working. Here I give my code which I have done.
function getusedcarFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateusedcar(opts){
$.ajax({
type: "POST",
url: "filter.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(data){
$('#usedcar1').html(makeTable(data));
displayRecords();
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getusedcarFilterOptions();
updateusedcar(opts);
});
updateusedcar();
// fetching records
function displayRecords(numRecords, pageNum) {
$.ajax({
type: "GET",
url: "getrecords.php",
data: "show=" + numRecords + "&pagenum=" + pageNum,
cache: false,
beforeSend: function() {
$('.loader').html('<img src="loader.gif" alt="" width="24" height="24" style="padding-left: 400px; margin-top:10px;" >');
},
success: function(html) {
$("#usedcar1").html(makeTable(data));
$('.loader').html('');
}
});
}
// used when user change row limit
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
displayRecords(10, 1);
});
</script>
thanks in advance.
You should combine the codes on server side, otherwise the filtered record are not paginated and vice-versa. Otherwise you need to do the pagination on client side but I suppose it would eliminate the main reason of the pagination.

Categories