Stop a custom.js function - javascript

my admin-ajax.php file is causing quite a bit of server load and ending up with a 400 request. Ive honed in on the culprit which appears to be "action=wishlist_counter" caused by woocommerce. Although the cart is disabled its still causing issues. The code in question is found in my themes custom.js file and appears as is below;
/*************************************************************
WOOCOMMERCE WISHLIST
*************************************************************/
function to_wishlist_count() {
$.ajax({
type: 'POST',
url: to_ajaxurl,
data: {action : 'wishlist_counter'},
success:function(data) {
$('.to-wishlist-number').html(data);
if(parseInt(data) === 0 ) {
$('.to-wishlist-counter').animate({top:'-100%'}, 0);
} else {
$('.to-wishlist-counter').animate({top:0}, 400);
}
}
});
}
$(document).ready(function() {
to_wishlist_count();
});
$(document).on('click', '.product-remove a', function() {
setTimeout(function() {
to_wishlist_count();
}, 1500);
});
$(document).on('click', '.add_to_wishlist', function(){
var $this = $(this);
var productAdded = $this.parents('li.product').find('h3').text();
if (productAdded == '') {
productAdded = $('h1').text();
}
$('.wishlist-notification .item-product').html('"'+productAdded+'"');
$this.parents('li.product').find('.product-img-wrap div.loading').fadeIn(100);
setTimeout(function(){
$('.to-wishlist-number').html(parseInt($('.to-wishlist-number').html())+1);
$this.parents('li.product').find('.product-img-wrap div.loading').fadeOut(100);
$('#header .wishlist-notification').fadeIn(400);
setTimeout(function(){
to_wishlist_count();
$('#header .wishlist-notification').fadeOut(400);
},2250);
},500);
});
})(jQuery);
What would be the best way of removing this code or ceasing it from its dastardly activities. Removing it from the file? or perhaps a function of sorts?

Related

The second ajax request does not change the DOM after loading the first one jQuery

I have two very similar jquery AJAX codes. Both work correctly when I use them separately. However, if I load the first code, if I want to load the second it probably works (because I tested different places "console.log(''test'')"), but it doesn't change the DOM. Please help.
I have tried many different solutions and none have provided a solution. I have searched on many forums but have not found an answer.
1st
var basketAddTimeout;
var ajaxSubmitForm;
app_shop.run(function() {
ajaxSubmitForm = function() {
$this = $('#projector_button_basket');
var url = $('#projector_form').attr('action');
var txt = $this.text().trim();
clearTimeout(basketAddTimeout);
$.ajax({
type: 'POST',
url: url,
data: $('#projector_form').serializeArray(),
success: function(data) {
basketAddTimeout = setTimeout(function() {
$('#Basket').load(' #projector-basket-form');
}, 1000)
fetch('/ajax/basket.php').then(res => res.json()).then(({
basket
}) => {
const number = basket.productsNumber;
const number12 = basket.worth_formatted;
$('#kwota-basket').text(number12);
document.getElementById('badgekoszyka').style.display = 'block';
$( "#badgekoszyka" ).fadeOut( "slow");
$( "#badgekoszyka" ).fadeIn( "slow");
$('#menu_basket .badge').text(number);
$('#badgekoszyka').text(number);
})
},
error: function() {
classObj.alert(classObj.txt.dodano_produkt_blad);
$('#projector_button_basket').html(txt);
$('#projector_button_basket').removeClass('loader');
}
});
}
}, 'all');
second
var basketAddTimeout2;
var ajaxSubmitForm2;
app_shop.run(function() {
ajaxSubmitForm2 = function() {
var url = $('#projector-basket-form').attr('action');
$('#loaders').addClass('loader-koszyk');
$('#blok-koszyk').css('filter','blur(3px)');
clearTimeout(basketAddTimeout2);
$.ajax({
type: 'POST',
url: url,
data: $('#projector-basket-form').serializeArray(),
success: function(data) {
basketAddTimeout2 = setTimeout(function() {
}, 1000)
fetch('/ajax/basket.php').then(res => res.json()).then(({
basket
}) => {
const number = basket.productsNumber;
const number12 = basket.worth_formatted;
$('#kwota-basket').text(number12);
$('#menu_basket .badge').text(number);
$('#badgekoszyka').text(number);
$('.topBasket').load('/basketchange.php?type=multiproduct&mode=2 .topBasket>*', function() {});
$('#loaders').removeClass('loader-koszyk');
$('#blok-koszyk').css('filter','blur(0px)');
document.getElementById("Basket").innerHTML = contentt;
})
},
error: function() {
classObj.alert(classObj.txt.dodano_produkt_blad);
}
});
}
}, 'all')
$(document).on('click', '#usuwanie-koszyk, #dodawanie-koszyk, #usuwanie-calkowite ', function(e) {
ajaxSubmitForm2();
e.preventDefault();
});
You Should call e.preventDefault() at the priority to defend the default action on the element in the second request.
$(document).on('click', '#usuwanie-koszyk, #dodawanie-koszyk, #usuwanie-calkowite ', function(e) {
e.preventDefault()
ajaxSubmitForm2()
});

Animation effect before ajax call

I've watched several tutorials on how to load content without having to refresh the browser. I'm also using history pushState and popstate to update the url dynamically depending on what site that is displaying. However even if this code works, I would like to be able to make som page transition animation effects > call the Ajax function > then make some fadeIn animation effects. So far i've had no luck in trying to do so. I tried to read up on Ajax (beforeSend: function(){}), but the success function seems to execute before the (beforeSend) function. Is there anyone that could point me in the right direction, or tell me what i possibly am doing wrong? I'd appriciate it!
$(document).ready(function() {
var content, fetchAndInsert;
content = $('div#content');
// Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
}
});
};
// User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
$('.buttonlink').click(function(){
var href = $(this).attr('href');
// Manipulate history
history.pushState(null, null, href);
// Fetch and insert content
fetchAndInsert(href);
return false;
});
});
Questions? Just ask!
Thanks beforehand!
/// E !
You need to use callbacks. The provided solutions will work, but not necessarily sequentially. $.animate() and $.ajax both run asynchronously. If unfamiliar with this term, here's a good intro: http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027
Here's what I might do:
fetchAndInsert = function(href) {
$('#some-element').animate({'opacity':'0.0'}, 1000, function () {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
content.animate({'opacity':'1.0'}, 1000);
}
});
});
};
That will fade out whatever is currently in content, fetch the new data, replace what's currently in content, and then fade back in.
I tried to read up on Ajax (beforeSend: function(){}), but the success
function seems to execute before the (beforeSend) function
You can wait for animation to complete before appending new content to html using .queue(), .promise(), .finish()
beforeSend: function() {
element.queue(function() {
$(this).animate({/* do animation stuff */:500}, {duration:5000}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
container.append(content).fadeIn()
})
}
var element = $("#loading").hide();
var container = $("#content");
var button = $("button");
var ajax = {
// do asynchronous stuff
request: function() {
return new $.Deferred(function(d) {
setTimeout(function() {
d.resolve("complete")
}, Math.random() * 5000)
})
},
beforeSend: function() {
element.fadeIn().queue(function() {
$(this).animate({
fontSize: 100
}, {
duration: 2500
}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
element.fadeOut("slow", function() {
$(this).css("fontSize", "inherit");
container.append(content + "<br>").fadeIn("slow");
button.removeAttr("disabled")
})
})
}
}
button.click(function() {
$(this).attr("disabled", "disabled");
$.when(ajax.beforeSend()).then(ajax.request).then(ajax.success)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="loading">loading...</div>
<div id="content"></div>
<button>load content</button>
jsfiddle https://jsfiddle.net/ajmL5g1a/
Try this:
fetchAndInsert = function(href) {
// Before send ajax. Do some effects here
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
// After loading. Do some effects here
content.html(data);
}
});
};
My solution:
fetchAndInsert = function(href) {
var timeBeforeAnimation = Date.now(), animationDuration = 500;
/* Do some animation, I assume that with jQuery,
so you probably know how much time is takes - store that
time in variable `animationDuration`. */
/* Run your "before" animation here. */
$.ajax({ ...,
success: function(data) {
/* Check, if request processing was longer than
animation time... */
var timeoutDuration = animationDuration -
(Date.now() - timeBeforeAnimation);
/* ...and if so, delay refreshing the content,
and perform the final animation. */
setTimeout(function() {
content.html(data);
/* Perfom final animation. */
}, Math.max(0, timeoutDuration);
}
});
};
I would probably try using some css for this.
#content {
opacity: 0;
transition: all 1s;
}
#content.fade-in {
opacity: 1;
}
...
const content = $('#content');
const btn = $('.buttonlink');
const success = data =>
content.html(data).addClass('fade-in');
const fetchAndInsert = url =>
$.ajax({ url, cache: 'false' }).done(success);
const getData = function(e) {
e.preventDefault();
content.removeClass('fade-in');
fetchAndInsert($(this).attr('href'));
};
btn.on('click', getData)

My jQuery ajax if/else on click is not working

So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});

Reinitialise JScrollPane after AJAX post loading

Im'm loading posts in a div #reviewspostscont, the AJAX code works and the posts are loaded when the scrollbar gets to the end but I can't reinitialise JScrollPane to show them.
I tried different codes but nothing works, this is what i have so far.
Thanks in advance, Matt
jQuery(document).ready(function($) {
$(function()
{
$('#reviewspostscont').each(
function()
{
$(this).jScrollPane(
{
horizontalDragMaxWidth : 100
}
);
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind(
'resize',
function()
{
if (!throttleTimeout) {
throttleTimeout = setTimeout(
function()
{
api.reinitialise();
throttleTimeout = null;
},
50
);
}
}
);
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight)
{
var count = 2;
if (isAtRight == true) {
loadArticle(count);
var api = $(this).data('jsp');
api.reinitialise();
count++;
}
}
);
}
)
});
function loadArticle(pageNumber){
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop-reviews',
success: function(html){
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});
You can use autoReinitialise. Here's a demo showing a similar example. And another one. And another.

Infinite Scroll with JScrollPane in Wordpress

I've done AJAX post loaders before but I'm having quite an hard time with jScrollPane.
Two things:
where should I load the posts? the div i created (#reviewspostscont) or .jspPane that JScrollPane makes? what if i have multiple loops then?
a more practical one now, this is the code i have so far, I can't get the function that triggers the AJAX to get the isAtRight variable (undefined in console), any fix?
Thanks in advance, Matt
$(function() {
$('#reviewspostscont').each(function() {
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight) {
console.log('Handle jsp-scroll-x', this,
'scrollPositionX=', scrollPositionX,
'isAtLeft=', isAtLeft,
'isAtRight=', isAtRight);
}
);
$(this).jScrollPane({ horizontalDragMaxWidth: 100 });
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind('resize', function() {
if (!throttleTimeout) {
throttleTimeout = setTimeout(function() {
api.reinitialise();
throttleTimeout = null;
}, 50);
}
});
});
$('#reviewspostscont').scroll(function() {
var $this = $(this);
var scrollWidth = $this[0].scrollWidth - $this.width();
var scrollPercentage = $this.scrollLeft() / scrollWidth * 100;
if (isAtRight == true) {
loadArticle(count);
count++;
}
});
function loadArticle(pageNumber) {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
success: function(html) {
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});

Categories