I'm trying to find out why when a user is deleted by clicking on the ajax-delete class icon and performs the deletion process it shows the gritter message after deletion however if you were to immediately delete another user afterwards it removes the previous gritter message but doesn't show another for that second deletion. Any ideas on why this could be?
EDIT: I have figured out that the issue belongs to the $.gritter.removeAll(); code line. When there is another existing notification it removes it but doesn't add the next notification.
Any ideas what I should do here?
var rowToDelete = null;
var basicTable = null;
var api_url = null;
$(document).ready(function() {});
$(document).on('click', '.ajax-delete', function(e)
{
console.log(basicTable);
e.preventDefault();
//defining it like this captures and optimizing the need to cycle over the DOM more than once
//in subsequent calls to the element specifically
$elem = $(this);
$parentElem = $elem.closest('tr');
rowToDelete = $parentElem.get(0);
api_url = $elem.attr('href');
runConfirmation($('td:eq(1)', $parentElem).text());
});
function runConfirmation(nameSting)
{
$mymodal = $('#myModal');
$('.modal-body p', $mymodal).html('Are you sure you want to delete this <strong>'+nameSting+'</strong>?');
$mymodal.modal('show');
}
$('#myModalConfirm').on('click', function(e) {
$.ajax({
type: 'post',
url: api_url,
data: { _method: 'DELETE' },
dataType: 'json',
success: function(response) {
$.gritter.removeAll();
var className = 'growl-danger';
if (response.status == "SUCCESS") {
className = 'growl-success';
basicTable.fnDeleteRow(basicTable.fnGetPosition(rowToDelete));
rowToDelete = null;
api_url = null;
}
$.gritter.add({
position: 'top-right',
fade_in_speed: 'medium',
fade_out_speed: 2000,
time: 6000,
title: response.title,
text: response.message,
class_name: className,
sticky: false
});
}
});
$('#myModal').modal('hide');
});
Replace the following line:
$.gritter.removeAll();
With
$('.gritter-item-wrapper').remove();
Related
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()
});
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)
Working with a modal form that submits edited information via ajax post. The thing is, it submitted once the first time .. fire up the modal form again, then submit, and twice it goes and so on and so forth. Does anyone had this sort of experience before? Please help.
$("#editInfo").click(function () {
valform = ["realname","email"];
valneed = 2;
$('#smallModal .modal-body').empty();
$('#smallModal .modal-body').load('/profile.php?action=profile_edit_info');
$('#smallModal .modal-title').text('Edit Personal Information');
$('#smallModal').modal('show')
$('#smallModal').on('shown.bs.modal', function () {
$("#smallModal #profileeditinfoform").keydown(function(event){
if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
{
event.preventDefault();
return false;
}
});
$("#realname_comment").hide();
$("#email_comment").hide();
$('#realname').bind("change", function() {
$('#realname').addClass("spinner");
var v_realname = verifyVar($('#realname').val(),'name');
displayVerify(v_realname,'realname');
});
$('#email').bind("change", function() {
$('#email').addClass("spinner");
var v_email = verifyVar($('#email').val(),'email');
displayVerify(v_email,'email');
});
$("#editinfo_submit_btn").click(function(event) {
event.preventDefault();
$('#loader').fadeIn();
formData = $("#profileeditinfoform").serialize();
var v_submit = submitEditInfo(formData);
verifySubmitEditInfo(v_submit);
$('#loader').fadeOut();
});
});
});
function submitEditInfo(data) {
var alldata = data + '&action=profileeditinfo';
return $.ajax({
type: 'POST',
cache: false,
data: alldata,
url: '/ajax/submit.php'
});
}
function verifySubmitEditInfo(ajaxCall) {
ajaxCall.success(function(realData) {
response = JSON.parse(realData)
if (!response.success) {
$.gritter.add({
title: response.title,
image: '/img/custom/fail.png',
sticky: false,
text: response.message
});
} else {
valform = [];
$("#submitdiv").hide();
$("#profileeditinfoform").find("input:text").val('');
$('#infodiv').slideUp(200).load('/divloader.php?req=profile_info').slideDown(200);
$.gritter.add({
title: response.title,
image: '/img/custom/success.png',
sticky: false,
text: response.message
});
$("#smallModal").modal('hide');
}
});
}
Every time you click, you're adding a new event handler:
$('#smallModal').on('shown.bs.modal' //...
Are you sure you want to do this on "click", or might it be better to set this up outside of the click handler?
In fact, you're binding event handlers as a response to other events all over this code. That's probably not a great idea, unless you unbind them once you're done.
You need to pull out your binders, you bind a new time every time the button is clicked! Only bind on load, not under button click event.
I have a submit button on page index.php When i click this button another script (call.php) is called through ajax that holds some response. Now i want that time between the click of submit button and response displayed/received under a div through the call of ajax script the buttons option1 and option2 should get disabled. and when succesfully the result is dispalyed the 2 buttons should get enabled, however i am not able to do so. can anyone help me with it
3 buttons and script code on index.php page is
<button class="rightbtn" type="button" id="submitamt" style="display:none; ">Submit</button>
<button class="botleftbtn" type="button" id="walkaway" style="display:none">Option1</button>
<button class="botrightbtn" type="button">Option2</button>
<script>
function myFunction() {
alert("You need to login before negotiating! However you can purchase the product without negotiating");
}
var startClock;
var submitamt;
var walkaway;
var digits;
$(function() {
startClock = $('#startClock').on('click', onStart);
submitamt = $('#submitamt').on('click', onSubmit);
walkaway = $('#walkaway').on('click', onWalkAway);
digits = $('#count span');
beforeStart();
});
var onStart = function(e) {
startClock.fadeOut(function() {
startTimer();
submitamt.fadeIn(function() {
submitamt.trigger('click'); // fire click event on submit
});
walkaway.fadeIn();
});
};
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
var onWalkAway = function(e) {
//console.log('onWalkAway ...');
};
var counter;
var timer;
var startTimer = function() {
counter = 120;
timer = null;
timer = setInterval(ticker, 1000);
};
var beforeStart = function() {
digits.eq(0).text('2');
digits.eq(2).text('0');
digits.eq(3).text('0');
};
var ticker = function() {
counter--;
var t = (counter / 60) | 0; // it is round off
digits.eq(0).text(t);
t = ((counter % 60) / 10) | 0;
digits.eq(2).text(t);
t = (counter % 60) % 10;
digits.eq(3).text(t);
if (!counter) {
clearInterval(timer);
alert('Time out !');
resetView();
}
};
var resetView = function() {
walkaway.fadeOut();
submitamt.fadeOut(function() {
beforeStart();
startClock.fadeIn();
});
};
</script>
You can achieve this by disabling the buttons before you make the AJAX request, and then enabling them again in the complete handler of the request. Try this:
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$('.botleftbtn, .botrightbtn').prop('disabled', true); // < disable the buttons
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
},
complete: function() {
$('.botleftbtn, .botrightbtn').prop('disabled', false); // < enable the buttons
}
});
};
Note that its best to enable the buttons in the complete handler and not the success handler. This is because if there is an error the buttons will never be enabled again.
Disable the buttons on click, and enable them on ajax success:
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
//Disable buttons ---------------------- //
//Give an id to the second button
$('#walkaway, #the_other_button').prop('disabled', true);
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
//Enable buttons ---------------------- //
$('#walkaway, #the_other_button').prop('disabled', false);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
In your onsubmit() code, get a var reference to the buttons you wish to deactivate
Var btn1 = document.getElementbyId("btn1");
But you would have to set an Id for the two buttons.
You can disable these in your submit code and then enable them when your timer is done.
Btn1.disabled = true;
When your timer is done, set it as false the same way.
I have a cookie which I would like to read then remove one entry from it based in the widget ID.
if (thisWidgetSettings.removable) {
$('CLOSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$.ajax({
type: "get",
url: "/controllers/widget.php",
data: {
method: "remove",
widgetID:thisWidget.id,
},
dataType: "json",
});
var mycookie = $.cookie("mypreferences");
//remove based on id here
as suggested...
var cookieName = 'myCookie';
var cookie = $.cookie("preferences");
var cookie = cookie.split('|');
$(cookie).each(function(index){
var thisCookieData = this.split(',');
alert(thisCookieData);
});
use split() to get individual elements from your cookie and than loop through them, and remove it. and then combine the rest of your entries and save it.
split reference:
http://www.w3schools.com/jsref/jsref_split.asp