Reset idleTimeout counter between ajax post - javascript

I am using JQuery idleTimeout plugin from here :
http://www.erichynds.com/examples/jquery-idle-timeout/example-mint.htm
I'm using it in an mvc 4 application.
Below is the code snippet where i set the session timer.
<script type="text/javascript">
var sessionTimer = 60;
$(document).ready(function ()
{
// setup the dialog
$("#dialog").dialog({
autoOpen: false,
modal: true,
width: 400,
height: 210,
closeOnEscape: false,
draggable: false,
resizable: false,
buttons: {
'Yes, Keep Working': function () {
$(this).dialog('close');
},
'No, Logoff': function () {
// fire whatever the configured onTimeout callback is.
// using .call(this) keeps the default behavior of "this" being the warning
// element (the dialog in this case) inside the callback.
$.idleTimeout.options.onTimeout.call(this);
}
}
});
var $countdown = $("#dialog-countdown");
#* start the idle timer plugin *#
$.idleTimeout('#dialog', '#dialog-button-yes', {
idleAfter: (sessionTimer - 30),
keepAliveURL: '#Url.Action("KeepAlive", "Home")',
pollingInterval: 5,
serverResponseEquals: 'OK',
AJAXTimeout: 250 * 60,
onTimeout: function () {
window.location = '#Url.Action("Logout", "Login")';
},
onIdle: function () {
$(this).dialog("open");
},
onCountdown: function (counter) {
$countdown.html(counter); #* update the counter *#
}
});
});
This code is placed in the outermost/shared view. All my pages are loaded using partial views using jquery $.ajax. The above code is loaded only once, the sessionTimer gets set to 60 seconds. So the timer does not resets when a new page gets loaded calling ajax post. Even though the user is active, the timer is ticking between the posts.
Is there a way for me to reset the counter every time an ajax post takes place.
I can reset this on every inner views $.ajax success condition. But there are too many places. I would like to know if there is a common code I can write on this master page of mine, that will let me know that an ajax call has been placed and to reset the counter.

Try using the .ajaxSuccess() event handler from jQuery. You can check the documentation on how to use it here: http://api.jquery.com/ajaxsuccess/ .

Related

Javascript functions executes on second time

I am using the jQuery webcam plugin to capture an image from the webcam. I have all script files in order. This button is used to make the capture() call to get the webcam's snapshot:
<input id="capture" type="submit" value="Capture my shot!" onclick="webcam.capture();" />
The webcam is called through the following function:
$("#cam-space").webcam({
width: 560,
height: 420,
mode: "save",
swffile: "javascript/jscam.swf",
onTick: function (remain) {
if (0 == remain) {
jQuery("#timer-status").text("Cheese!");
} else {
jQuery("#timer-status").text(remain + " seconds remaining...");
}
},
onSave: function () {
},
onCapture: function () {
webcam.save("/capture/image");
},
debug: function () { },
onLoad: function () { }
});
My problem is that when I clicked the button the first time, I'm getting the following error in Chrome's debugger:
Uncaught TypeError: undefined is not a function (onclick)
But when I click it the second time, it works and takes the snapshot. What may be the problems?
The function webcam.capture() won't be defined until the Webcam plugin finishes loading. Instead of using an onclick attribute on the button, you should bind the event listener after the plugin is loaded:
$("#cam-space").webcam({
/* ... */
onLoad: function() {
$("#capture").on("click", webcam.capture);
}
/* ... */
});
Additionally, as Mritunjay suggested in the comments, make sure your $("#cam-space").webcam() statement is contained in $(document).ready(function() { });.

Redirect not always working with JQuery UI Dialog

I am having some issues getting the jquery ui dialog redirecting always. When I click a delete link it asks if you are sure. If you click the delete button it should be redirected. THe problem is it doesnt always redirect the first time. It usually only works after you click the dialog window delete the second time. Does anyone know why this might happen? I have tried using the redirect in multiple places including after the query happens and before and after the delete query closes.
Page where dialog redirects(at bottom);
Delete
<script>
var id = "";
//run function after jquery dialong confirm
//step 1 - the action
$(".delete").click(function(e) {
e.preventDefault();
id = $(this).parent().attr('id');
//console.log(id); // check you get it first
$('#dialog').dialog('open');
});
//step 2 - the dialog modal
$("#dialog").dialog({
resizable: true,
height: 100,
modal: true,
autoOpen: false,
buttons: {
"Delete": function() {
//console.log(id + " made it to dialog"); // make sure our id makes it this far
deleteUser(id); // run delete photo function
window.location.href = "http://www.speechvive.com/adminSLP.php";
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
//step 3 - php function
function deleteUser(user_id) {
//console.log(user_id + " made it to function"); // make sure our id makes it this far
$.ajax({
type: "POST",
url: "/adminSLP.php#delete",
data: {user_id: user_id}
}).done(function(msg) {
console.log(msg);
//no message bc we did a fadeOut
//var msg would show any errors from our php file
});
}
;
</script>

Function triggering before I select a date in datepicker

I need the help of the experts on here.
When I call the function v9_insert_comments('1') the alert(sdate) triggers before I even get to select a date in the datepicker.
My goal is to have the v9_insert_comments() check to see if the sdate is null or not. If its null then just { return } if not { do something else }.
The current case if that sdate is always null because the datepicker never gets a chance to set it.
var sdate
//========================================================================
function v9_insert_comments(x) {
//========================================================================
if (x == 1) {
select_date()
alert(sdate)
}
}//end of function
//========================================================================
function select_date() {
//========================================================================
$('#dd').dialog({
autoOpen: true,
modal: true,
overlay: {
opacity: 0.5,
background: 'black'
},
title: "title",
height: 265,
width: 235,
draggable: false,
resizable: false
}); //end of dialog
$('#d1').datepicker({
onSelect: function() {
sdate = $(this).val();
$("#dd").dialog("close");
}
});
} //end of function
Body:
<!-- START OF DATE SELECTOR DIALOG -->
<div style="display:none" id="dd">
<div id="d1"></div>
</div>
<!-- END OF DATE SELECTOR DIALOG -->
In your select_date method you're just setting stuff up. The call to $('#dd').dialog() does all the jQuery UI magic to create a dialog, by updating the DOM and wiring things up. Then you call $('#d1').datepicker(), which sets up a datepicker in a similar way. It's just saying "this div is now a dialog, and this div is now a datepicker". It's not waiting for any user interaction. Your v9_insert_comments function is assuming things are happening synchronously, whereas they're actually happening asynchronously.
After these things are set up, you immediately ask for the value of a variable that hasn't been set yet. It hasn't been set because the anonymous function you supplied for the datepicker's onSelect event hasn't fired yet. This function will only be called when something has been selected in the datepicker. So if you want to do something with the selected date, do it in the event handler.
You could move your alert to the event handler, or you could call v9_insert_comments from the event handler - but in this case you should move the call to select_date elsewhere. The dialog and datepicker only need to be set up once.

javascript setInterval() inside jQuery dialog not stopping on destroy or remove

I have a jQuery dialog that appears and loads an external page. In that page i am running a setInterval() function that queries my server continuously every 1 second (AJAX). The problem is that when i close the dialog, the setInterval doesn't stop running.
here is the code for the dialog:
var theUrl = 'someUrl';
var popUp = document.createElement('div');
$(popUp).dialog({
width: 400,
height: 270,
title: "Some Title",
autoOpen: true,
resizable:false,
close: function(ev, ui) {
$(this).dialog('destroy');
},
modal: true,
open: function() {
$(this).load(theUrl);
}
});
I tried calling $(this).dialog('destroy') and $(this).remove() and document.body.removeChild(popUp) on close. nothing worked. is there anyway to 'unload' the loaded page?
setInterval returns a handler that you can pass to clearInterval to stop the function from running. Here's a basic example of how it works.
var handler = setInterval(function() {}, 2000);
clearInterval(handler);
For your example you'd want to call clearInterval in the close method of the ui.dialog.
Docs:
setInterval - https://developer.mozilla.org/en/window.setInterval
clearInterval - https://developer.mozilla.org/en/DOM/window.clearInterval
Edit
You will not be able to call clearInterval without the stored handler from setInterval, therefore if the call to setInterval is in another script the only way you're going to capture the handler is to override window.setInterval itself.
$(function() {
var originalSetInterval = window.setInterval;
var handlers = [];
window.setInterval = function() {
handlers.push(arguments[0]);
originalSetInterval(arguments);
};
$('whatever').dialog({
close: function() {
for (var i = 0; i < handlers.length; i++) {
clearInterval(handlers[i]);
}
handlers = [];
}
});
});
Note that the code to override window.setInterval must come before including the <script> tag to bring in the external file. Also this approach will clear all interval functions whenever clearInterval is called, therefore this is not ideal, but it's the only way you're going to accomplish this.

JQuery confirmation dialog after pressing the submit button but before POSTing with .ajax()

I have a very simple scenario where I want to POST the form using JQuery's ajax() method but perform request some confirmation from the user before actually performing the post.
I have a JQuery UI dialog with localized buttons in place in case you wonder what all the code with buttons below is about.
This is my code so far:
var i18n_deleteButtons = {};
i18n_deleteButtons[i18n.dialogs_continue] = function () {
return true;
$(this).dialog('close');
};
i18n_deleteButtons[i18n.dialogs_cancel] = function () {
return false;
$(this).dialog('close');
};
$('#delete-dialog').dialog({
open: function () {
$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
},
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: i18n_deleteButtons
});
$("form#form_attachments").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this), url = $form.attr('action');
// build array of IDs to delete (from checked rows)
var jdata = { 'attachmentIdsToDelete': [] };
$('input:checked').each(function () {
jdata['attachmentIdsToDelete'].push($(this).val());
})
$.ajax({
beforeSend: function (request) {
// Return false if you don't want the form submit.
$('#delete-dialog').dialog('open');
},
url: url,
type: "POST",
dataType: "json",
data: jdata,
traditional: true,
success: function (msg) {
$('#msg').html(msg);
}
});
});
The dialog actually opens up fine but clicking at any of the buttons results in nothing happening. The post doesn't happen and the dialog does not close regardless of which button was clicked.
How can I make this work?
Why not move the actual ajax call from the submit handler and trigger it when pushing a button in the delete dialog?
You could store you ajax call in a separat function and pass this functions and the url as parameters to the confirmation routine.
[pseudo code]
function callAjax() {
...
}
function submitHandler() {
confirmDialog({callback:callAjax,param:you_url});
}
function confirmDialog(obj) {
$('#yes_btn').click(function() {
// call the callback
obj.callback(obj.param);
});
$('#no_btn').click(function() {
// just close the dialog
});
}
This way the confirmDialog don't have to know anything about the ajax call, it will just execute the callback with the given parameter when the user clicks ok.
Because the default jquery UI dialog is a bit cumbersome for regular use and trouble to configure in some custom scenarios I looked around and found this Easy Confirm plugin which is based upon jquery&jquery UI default stuff. It also allows for very simple internationalization.
https://github.com/wiggin/jQuery-Easy-Confirm-Dialog-plugin

Categories

Resources