JQUERY 1.9 ,1.10, 1.11 conflict with code - javascript

I have this piece of code , that does not work , if I link JQUERY above 1.8.0
Just for curiosity, why its happening?
it takes values from select boxes, passing to pagination.php file and in the meantime showing loading image
// Pagination
$(document).ready(function () {
function loading_show() {
$('#loading').html("<img src='img/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading').fadeOut('fast');
}
function loadData(page) {
var house_id = $("#pbthouse option:selected").val();
var sale_id = $("#pbtsale option:selected").val();
var year_id = $("#pbtsale option:selected").val();
var ipp = $("#res option:selected").val();
loading_show();
$.ajax({
type: "POST",
url: "pagination.php",
//data: "page="+page,
data: {
page: page,
house_id: house_id,
year_id: year_id,
sale_id: sale_id,
ipp: ipp
},
success: function (msg) {
$("#container1").ajaxComplete(function
(event, request,settings)
{
loading_hide();
$("#container1").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container1 .pagination li.active').live('click', function () {
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click', function () {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if (page != 0 && page <= no_of_pages) {
loadData(page);
} else {
alert('Enter a PAGE between 1 and ' + no_of_pages);
$('.goto').val("").focus();
return false;
}
});
$('#container1 .pagination li.active').live('click', function () {
var page = $(this).attr('p');
loadData(page);
});
$("#pbthouses").change(function () {
var page = '1';
loadData(page);
});
$("#res").change(function () {
var page = '1';
loadData(page);
});
$('#pbtsale, #pbtyear').change(function () {
var sale_id = $("#pbtsale option:selected").val();
var sale_id = $("#pbtyear option:selected").val();
var page = '1';
if (sale_id != '') {
$.ajax({
type: "POST",
url: "get_pbtsales.php",
data: {
year_id: year_id,
sale_id: sale_id
},
success: function (option) {
$("#pbhouses").html(option);
loadData(page);
}
});
} else {
$("#pbhouses").html("<option value=''
>-- No category selected --</option>");
}
return false;
});
});

Support for .live() has been deprecated since version 1.7 and removed since version 1.9. You should switch to the dynamic form of .on() which would change from this:
$('#go_btn').live('click', function () {
to this:
$(document).on('click', '#go_btn', function () {
Ideally, instead of $(document), you would pick a closer parent of #go_btn that is static (e.g. not dynamically created) as this is more efficient than using $(document), particularly if you have a number of delegated event handlers like this.
Some references for delegated event handling with .on():
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Should all jquery events be bound to $(document)?
Does jQuery.on() work for elements that are added after the event handler is created?

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()
});

Debounce click on an AJAX link

Is it possible to debounce the click of a link? If a user clicks too many times too fast on a pjax link it'll break the load of new content.
$(document).on('click', 'a[data-pjax]', loadNewContent);
var $target = $('main.content section.context'),
$fake = $('main.fake'),
$fakeContext = $('main.fake section.context');
function loadNewContent() {
event.preventDefault();
var $this = $(this),
url = $this.attr('href');
$fake.addClass('is--loading');
$.pjax({
url: url,
fragment: 'body',
container: $fakeContext
});
$fake.one(transitionEnd, function() {
$target.html($fake.find('section.context').html());
$fake.removeClass('is--loading');
$fake.off(transitionEnd);
});
}
Any thoughts? I tried this, but it stopped the loadNewContent from firing. (https://github.com/cowboy/jquery-throttle-debounce)
$(document).on('click', 'a[data-pjax]', $.debounce(1000, true, function() {
loadNewContent();
}));
Something like this would work :
var callWaiting = false;
callAjax() {
if(!callWaiting) {
callWaiting = true;
makeHttpCall(url, data, function(response) {callWaiting = false;});
callWaiting = false;
}
}

My javascript function only fires once

I have a pretty basic step by step wizard I created. When you select an option from a drop down menu on page 1, I load a new page via jQuery ajax. If you hit back, it loads the original page again.
However after loading the original page again, my modelSelect() function that loads page 2 stops working. Doesn't fire at all. I'm not exactly sure what I'm doing wrong.
I'm hoping someone can see what I'm doing wrong. My code is below:
//Collapse panel handling
var group = jQuery('.estimator-container');
jQuery('.tab-click').click(function() {
group.find('.collapse.in').collapse('hide');
jQuery(this).parent().toggleClass('active');
});
/* -------------------------------------- *\
New form handler
\* -------------------------------------- */
function modelSelect(v) {
jQuery('#page_2, .estimator-container').toggle();
// Ajax for loading page_2
jQuery.ajax({
type: "POST",
data: v,
success: function() {
jQuery('.estimator-app').load(templateUrl + "/page-estimator2.php?p=" + v);
}
});
}
jQuery('.estimator-panel').on('change', '.select-model', function() {
var v = jQuery(this).val();
modelSelect(v);
}); //end on change function
// Back and continue handling
jQuery('.estimator-app').on('click', '.estimator_form_btn_next', function() {
var backBtn = jQuery('.estimator_form_btn_back');
var continueBtn = jQuery('.estimator_form_btn_next');
var firstPage = jQuery('#contact-first-page');
var lastPage = jQuery('#contact-last-page');
if (firstPage.is(":visible")) {
firstPage.toggle();
lastPage.toggle();
}
}); //end continue
// Go back
jQuery('.estimator-app').on('click', '.estimator_form_btn_back', function() {
var backBtn = jQuery('.estimator_form_btn_back');
var continueBtn = jQuery('.estimator_form_btn_next');
var firstPage = jQuery('#contact-first-page');
var lastPage = jQuery('#contact-last-page');
if (lastPage.is(":visible")) {
firstPage.toggle();
lastPage.toggle();
} else {
jQuery.ajax({
type: "POST",
// data: v,
success: function() {
jQuery('.estimator-app').load(templateUrl + "/estimator-initial.php");
}
});
}
}); //end continue
Simple delegation.
Adding jQuery(document).on('change', '.select-model', function(){ on line 29 made it work.
Change your this line:
jQuery('.estimator-panel').on('change', '.select-model', function() {
to this
jQuery(document).off('change', '.select-model').on('change', '.select-model', function(e){
e.preventDefault();
because if HTML is loaded after page load OR by some kind of JS, you need to deattach event and then attach back,

jQuery - preventDefault() in .each function

I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/

setInterval with other jQuery events - Too many recursions

I'm trying to build a Javascript listener for a small page that uses AJAX to load content based on the anchor in the URL. Looking online, I found and modified a script that uses setInterval() to do this and so far it works fine. However, I have other jQuery elements in the $(document).ready() for special effects for the menus and content. If I use setInterval() no other jQuery effects work. I finagled a way to get it work by including the jQuery effects in the loop for setInterval() like so:
$(document).ready(function() {
var pageScripts = function() {
pageEffects();
pageURL();
}
window.setInterval(pageScripts, 500);
});
var currentAnchor = null;
function pageEffects() {
// Popup Menus
$(".bannerMenu").hover(function() {
$(this).find("ul.bannerSubmenu").slideDown(300).show;
}, function() {
$(this).find("ul.bannerSubmenu").slideUp(400);
});
$(".panel").hover(function() {
$(this).find(".panelContent").fadeIn(200);
}, function() {
$(this).find(".panelContent").fadeOut(300);
});
// REL Links Control
$("a[rel='_blank']").click(function() {
this.target = "_blank";
});
$("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
$("#content").fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
}
}
This works fine for a while but after a few minutes of the page being loaded, it drags to a near stop in IE and Firefox. I checked the FF Error Console and it comes back with an error "Too many Recursions." Chrome seems to not care and the page continues to run more or less normally despite the amount of time it's been open.
It would seem to me that the pageEffects() call is causing the issue with the recursion, however, any attempts to move it out of the loop breaks them and they cease to work as soon as setInterval makes it first loop.
Any help on this would be greatly appreciated!
I am guessing that the pageEffects need added to the pageURL content.
At the very least this should be more efficient and prevent duplicate handlers
$(document).ready(function() {
pageEffects($('body'));
(function(){
pageURL();
window.setTimeout(arguments.callee, 500);
})();
});
var currentAnchor = null;
function pageEffects(parent) {
// Popup Menus
parent.find(".bannerMenu").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
subMenu: $(this).find("ul.bannerSubmenu"),
handlerIn: function() {
this.subMenu.slideDown(300).show();
},
handlerOut: function() {
this.subMenu.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
parent.find(".panel").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
content: panel.find(".panelContent"),
handlerIn: function() {
this.content.fadeIn(200).show();
},
handlerOut: function() {
this.content.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
// REL Links Control
parent.find("a[rel='_blank']").each(function() {
$(this).target = "_blank";
});
parent.find("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
var content = $("#content");
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
content.fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
pageEffects(content);
}
}
Thanks for the suggestions. I tried a few of them and they still did not lead to the desirable effects. After some cautious testing, I found out what was happening. With jQuery (and presumably Javascript as a whole), whenever an AJAX callback is made, the elements brought in through the callback are not binded to what was originally binded in the document, they must be rebinded. You can either do this by recalling all the jQuery events on a successful callback or by using the .live() event in jQuery's library. I opted for .live() and it works like a charm now and no more recursive errors :D.
$(document).ready(function() {
// Popup Menus
$(".bannerMenu").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find("ul.bannerSubmenu").slideDown(300);
} else {
$(this).find("ul.bannerSubmenu").slideUp(400);
}
});
// Rollover Content
$(".panel").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find(".panelContent").fadeIn(200);
} else {
$(this).find(".panelContent").fadeOut(300);
}
});
// HREF Events
$("a[rel='_blank']").live("click", function(event) {
var target = $(this).attr("href");
window.open(target, "_blank");
event.preventDefault();
});
$("a[rel='share']").live("click", function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
setInterval("checkAnchor()", 500);
});
var currentAnchor = null;
function checkAnchor() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn(200);
$("#content").fadeOut(200).html(data).fadeIn(200);
$("#load").fadeOut(200);
});
}
}
Anywho, the page works as intended even in IE (which I rarely check for compatibility). Hopefully, some other newb will learn from my mistakes :p.

Categories