Repeated Ajax calls using SetTimeout javascript, unexpected execution - javascript

I list of users in a html table that is dynamically created on page load. Each row has an inline button and each button has onclick="functionName(userId)", calls the following functions:On click show the bootstrap model pop up and then after starts calling ajax. The problem is stopping the ajax calls after user has closed model,and if user clicks on another row/user pass the current userId. for some reason, sometimes ajax calls stop and sometimes dont. Previous userId is also being saved somewhere which is resulting double or triple calls in a given interval. Thank you for your insights.
//This function gets called from each row passing its userId:
var timer = null;
function RTLS(id) {
$('#RTLSModal').modal('show');
window.clearTimeout(timer);
$('#RTLSModal').on('hidden.bs.modal',
function() {
window.clearTimeout(timer);
timer = 0;
$('#RTLSModal .modal-body').html("");
$('#RTLSModal').data('bs.modal', null);
});
$('#RTLSModal').on('shown.bs.modal',
function () {
GetRealTimeScans(id);
});
}
function GetRealTimeScans(id) {
var html = '';
$.ajax({
url: '/api/v1/computers/GetRealTimeKeys?computerId=' + id,
typr: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (scans) {
if (scans.length > 0) {
$.each(scans,
function (index, value) {
//create html
});
$('#RTLSModal .modal-body').html(html);
} else {
html += '<div class=""><h3 style="text-align: center;">No one around</h3></div>';
$('#RTLSModal .modal-body').html(html);
}
},
complete: function () {
timer = setTimeout('GetRealTimeScans('+id+')', 10000);
}
});
}

So abort the Ajax call so it stops
var timer = null;
var ajaxCall;
function cleanUp () {
if (timer) window.clearTimeout(timer);
if (ajaxCall) ajaxCall.abort()
}
and when you make the call
cleanUp()
ajaxCall = $.ajax({})
.done( function () {
ajaxCall = null
timer = window.setTimeout(function(){}, 10000)
});
And when you bind the events to the modal, you need to remove the previous event handler.
$('#RTLSModal')
.off('hidden.bs.modal shown.bs.modal')
.on('hidden.bs.modal', function() {})
.on('shown.bs.modal', function() {});

Related

Jquery - Getting trouble on double click because change in class

I have a button. onclick I am changing the class of that button but when I double click its changing class. All my functionality depend on current class
how to disable double click or make the request complete on first click.
function data() {
lastScrollTop = 0;
document.getElementById("expand-dataset-btn").disabled = false;
var id = event.target.id
var allChildern = null
if(!$(".id_"+event.target.id).hasClass('minus-symbol')){
$(".id_"+event.target.id).removeClass('plus-symbol').addClass('minus-symbol')
$.ajax({
},
success : function(result) {
}
});
}else{
$(".id_"+event.target.id).addClass('plus-symbol').removeClass('minus-symbol')
$.ajax({
},
success : function(result) {
}
});
}
}
Calling function from controller like below
htmlDataId += "<a onclick=\"data()\" title='View' id="+row[primaryField]+">
what you need is "throttle" function or "debounce" function.
Throttling is a means by which we can limit the number of times a function can be called in a given period. For instance, we may have a method that should be called no more than 5 times per second.
you can either use underscore underscore official website
or
you can use the following codes:
/*trigger specific eventhandler when the event is idle for specific time*/
function debounce(fn, delay, self) {
var timer = null;
return function () {
var context = self ? self : this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
//use in the following way
$input.on('click',debounce(clickCallback,250));
then if the second "click" event triggered within 250ms, it will be ignored
You should wait for ajax to complete
function data() {
lastScrollTop = 0;
document.getElementById("expand-dataset-btn").disabled = false;
var id = event.target.id;
var allChildern = null;
if($(".id_"+ id).hasClass("disable"))
{
event.preventDefault();
}
if(!$(".id_"+ id).hasClass('minus-symbol')){
//make control disable
$(".id_"+ id).addClass('disabled');
$.ajax({
},
success : function(result) {
//change here after success
$(".id_"+ id).removeClass('plus-symbol').addClass('minus-symbol');
//remove control disable
$(".id_"+ id).removeClass('disabled');
});
}else{
//make control disable
$(".id_"+ id).attr('disabled', true);
$.ajax({
},
success : function(result) {
//change here after success
$(".id_"+ id).addClass('plus-symbol').removeClass('minus-symbol');
//remove control disable
$(".id_"+ id).attr('disabled', false);
}
});
}
}

how restart Jquery function if not complete

How can I let my form alert re-start once the user re-click the button if the input still empty
What I made :
after the click it will check if the inputs empty will stop the code and show alert. but once the alert appeared if I re-click the button again its not work again!
$(document).ready(function(){
function requierd()
{
$('#allrequierd').addClass("animated");
$('#allrequierd').addClass("shake");
$('#alertDanger').removeClass("hide");
setTimeout( "$('#alertDanger').fadeOut();", 4000);
}
function pass()
{
$('#alertDanger').addClass("hide");
$('#alertsuccess').removeClass ("hide");
$('#visitorFullName').val('');
$('#visitorPhoneNumber').val('');
$('#visitorEmail').val('');
$('#visitorMsg').val('');
$('#alertsuccess').addClass ("animated");
$('#alertsuccess').addClass ("bounceIn");
setTimeout( "$('#alertsuccess').fadeOut();", 4000);
}
$('#sendContactMsg').click(function ()
{
var visitorFullName = $('#visitorFullName').val();
var visitorPhoneNumber = $('#visitorPhoneNumber').val();
var visitorEmail = $('#visitorEmail').val();
var visitorMsg = $('#visitorMsg').val();
var visitorCallMethod = $('#visitorCallMethod').val();
var dataString = 'visitorFullName='+visitorFullName+'&visitorPhoneNumber='+visitorPhoneNumber+'&visitorEmail='+visitorEmail+'&visitorMsg='+visitorMsg+'&visitorCallMethod='+visitorCallMethod;
if(visitorFullName==''||visitorPhoneNumber==''||visitorEmail==''||visitorMsg=='')
{
requierd();
}else{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "functions/sContactus.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
if (result == "Success") {
// alert("DONE");
pass();
}else {
alert("Sorry Try Again")
}
}
});
}
return (start);
});
// END jquery
});
When you fire the alert the first time, your #alertDanger is getting the .fadeOut() which will apply inline display:none style to that element. You're not removing that inline style at any point, and in fact you're also not adding back the "hide" class either, so your #alertDanger will remain hidden.
What you should do is "reset" the alert div after you fade it out:
function removeAlert() {
$('#alertDanger').fadeOut();
$('#alertDanger').addClass("hide").css("display","block");
}
And in your required() function:
setTimeout( removeAlert, 4000);

JavaScript timer is not working

I have created a file named ExtremeNotifications.js and added to the _Layout.cshtml master layout.
The ExtremeNotifications.js includes the following JavaScript code:
var extremeNotifications = extremeNotifications || {};
extremeNotifications = (function () {
var baseURL = document.baseURI;
var url = baseURL + 'api/usernotifications';
var isNotificationServiceStarted = false;
var timer;
function getPendingNotifications() {
$.ajax({ url: url, success: dataRetrieved, type: 'GET', dataType: 'json' });
}
function dataRetrieved(data) {
alert(data);
}
function startNotifications() {
if (!isNotificationServiceStarted) {
timer = setInterval(getPendingNotifications, 3000);
isNotificationServiceStarted = true;
}
}
function stopNotifications() {
clearInterval(timer);
isNotificationServiceStarted = false;
}
return {
start: startNotifications(),
getPendingNotifications: getPendingNotifications(),
isNotificationServiceStarted: isNotificationServiceStarted,
stop: stopNotifications()
}
})();
Then in my Home Index.cshtml I start the notifications with the following code and only if User.Identity.IsAuthenticated:
<script>
extremeNotifications.start();
</script>
So now when my page starts and I'm authenticated user I get an alert box in the first time but I never see another alert after 3 seconds.
Any comments?
You're close, but you're creating that returned object incorrectly:
return {
start: startNotifications,
getPendingNotifications: getPendingNotifications,
isNotificationServiceStarted: isNotificationServiceStarted,
stop: stopNotifications
};
By including the () after the function names, your code was calling the functions and returning their return values instead of returning references to the functions themselves.

Making sure my form isn't being submitted multiple times with jquery show/hide

So when someone hits Reply, I am attempting to pop-up a form to type your response. Once the form is submitted, it disappears until the next time you hit Reply.
This is working except after the 1st time, I am submitting the information twice. If I do it a third time, the form submits three times. Essentially what is happening is the previous form doesn't seem to be resetting after I hide it again.
I checked this website/google and have tried using reset() but it didn't work. Below is the code:
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = document.getElementById("m_id").value;
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
});
Rather than initializing the submit function on every click, move it outside the click function. jQuery may be creating an instance of it for each click.
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = $("#m_id").val();
});
The alternative is to unbind the click function before reusing it.
We want a reusable way to handle the state. We will save the state of the button in a boolean which gets turned on and off depending on the status of the request. The pattern is the following:
var isSending = false;
function onSubmit() {
isSending = true;
// Send data
}
function onComplete() {
// done sending data
isSending = false;
}
if (!isSending) {
onSubmit();
}
// When data sending is finished:
onComplete();
The above can be encapsulated in a more functional way that uses promises to manage the state. (jQuery AJAX functions all return a promise-like object):
function oneAtATimeFunction(promisedFunction) {
var pendingPromise;
function reset() { pendingPromise = null; }
return function() {
if (pendingPromise) { return pendingPromise; }
pendingPromise = promisedFunction.apply(promisedFunction, arguments)
.always(reset);
return pendingPromise;
}
}
function submitForm() {
return $.ajax({
url: '/foo',
method: 'POST',
data: { data: 'from form' }
});
}
$('#submit-button').on('click', oneAtATimeFunction(submitForm));
Adding a little flare to the UI We can add a way to turn on and off the submit button. First we will define a helper function to handle the on and off state:
function buttonEnable(enabled) {
$('#submit-button').attr('disabled', !enabled);
}
buttonEnable(false); // disable the button
buttonEnable(true); // enable the button
Putting it all together:
function onClick() {
buttonEnable(false);
return onSubmit()
.always($.proxy(buttonEnable, null, true));
// The above is also the same as:
// .always(function() { buttonEnable(true); });
}
$('#submit-button').on('click', oneAtATimeFunction(onClick));
To see this in action here is a JSBin example.

Synchronize blur and click events in JavaScript

I am finding it difficult to synchronize blur and click events. The scenario is as follows: I have a page in which i have a textbox and a button. Now I have a blur event handler for the textbox, which basically makes an AJAX request and updates some part of the page. Also I have a click handler for the button which does some other job.
Now the problem here is that since I have a blur event handler on the textbox, when I enter something in the text box and directly click the button, it fires both blur and click events (as expected). The problem is synchronizing the two since the click handler should only execute once the blur handler has returned (if there was any blur event).
Sample code is as follows:
$('#textbox').on('blur', function(){
//make an ajax request
});
$('#btn').on('click',function(){
//wait for the blur event to finish(if any)
// then execute the code
})
Try something like this:
http://jsfiddle.net/8m7j5/2/
var blurring = [];
var expecting = false;
$(document).ready(function () {
$('#textbox').on('blur', function () {
// make an ajax request
console.log("TEXTBOX BLURRED");
blurring.push(1); // Flag a new blur event
$.ajax({
url: "/echo/json/",
complete: function () {
setTimeout(function () { // Simulate AJAX request taking 2 seconds
console.log("AJAX REQUEST COMPLETE");
blurring.pop(); // Flag completed blur event
checkClick();
}, 2000);
}
});
});
$('#btn').on('click', function () {
// wait for the blur event to finish(if any)
// then execute the code
console.log("ACTUALLY CLICKED BUTTON");
expecting = true;
checkClick();
});
});
function checkClick() {
if (expecting && blurring.length < 1) {
console.log("CHECKING: EXPECTING CLICK AND NO MORE BLUR EVENTS");
expecting = false;
clickFunction();
} else {
console.log("CHECKING: EITHER NOT EXPECTING OR BLUR EVENT(S) STILL OCCURRING");
}
}
function clickFunction() {
console.log("EXECUTING CLICK FUNCTION");
// Put your actual click code here
}
What you actually want to happen when the button is clicked, put in clickFunction.
The code from ianpgall a bit improved:
var functionsToCall = [];
var ajaxRunning = false;
$(document).ready(function(){
$('#textbox').on('blur', function(){
ajaxRunning = true;
console.log("START AJAX REQUEST");
$.ajax({
url: "/echo/json/",
complete: function () {
setTimeout(function () { // Simulate AJAX request taking 2 seconds
console.log("AJAX REQUEST COMPLETE");
ajaxRunning = false;
fireStackedCalls();
}, 5000);
}
});
})
$('#btn').on('click',function(){
if(ajaxRunning === true) {
functionsToCall.push('clickFunction()');
} else {
clickFunction();
}
});
function fireStackedCalls() {
while(functionsToCall.length > 0) {
toCall = functionsToCall.pop();
eval(toCall);
}
}
function clickFunction() {
console.log("EXECUTING CLICK FUNCTION");
// Put your actual click code here
}
});
Now every call of the clickFunction is recorded and executed if the ajax request is done.

Categories

Resources