Ext js client request for session active spring - session

I need to check is session is still active on my client side. Are there any request possible which would not extend the session? I could use then this request to check if session is still active. Please provide suggestion I have no clue how to overcome this.

You can use setInterval function with ExtJS Ajax request to check active session that you specified time.
var checkSession = Ext.Ajax.request({
// the following url must response a value based on the
// user session status, long story short
// you should define a function in Grails
url: '/grails_url/function',
method: 'POST',
success: function (response) {
Ext.Msg.show({
title: 'Session Expired...',
msg: 'You session has been expired!',
width: 300,
height: 200,
closable: false,
buttons: Ext.Msg.INFO,
buttonText: { ok: 'OK'},
icon: Ext.Msg.INFO,
fn: function(btn) {
if (btn == 'ok') {
window.location.href = 'http://www.domain.com/login';
}
}
})
}
});
// check session for every 5 sec
setInterval(checkSession, 5000);

Related

Kendowwindow __RequestVerificationToken

I am opening an kendo window using the below jquery function.
I need to pass __RequestVerificationToken to the MVC Controller because I am having ValidateAntiForgeryToken Attribute.
However, I am not able to pass it. Can you please suggest how to pass __RequestVerificationToken while opening an kendoWindow
function OpenTest() {
var url = '#Url.ActionWithArea("OpenTest", "Test", GlobalConst.AREA_Test)';
url += "?test=" +$("#test").val() +
"&test1=" +$("#test1").val();
windowElement = $('<div id = "abc" />').kendoWindow({
title: 'test',
content: url,
modal: true,
resizable: false,
draggable: false,
width: 900,
height: 400,
close: function () { windowElement.destroy(); }).data("kendoWindow").center().open();
return false;
}
You might want to think about including this token at a more global scope in your application so you don't have to meddle with it on a per call basis.
There is an example over on the Kendo UI forums, about halfway down. The data signature of your route should look like:
transport: {
read: {
url: url,
type: "POST",
data: {__RequestVerificationToken: $("input[name=__RequestVerificationToken]").val()
}
}
Or in your case, something like this -->
'#Url.ActionWithArea("OpenTest", "Test", new { __RequestVerificationToken=<value> }),GlobalConst.AREA_Test)';

Kendo get data from remote service, do paging locally

Code:
var url = base_url + "/api/v1/users/getUsers";
var dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: 'GET',
url:url,
dataType: 'json',
data: { searchTerm: $("#searchTerm").val().trim() },
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
}
},
schema: {
data: function (result) {
return result.model;
},
total: function (result) {
return result.model.length;
},
},
pageSize: 5
});
$("#matches").kendoListView({
dataSource: dataSource,
autoBind: false, // if set to false the widget will not bind to the data source during initialization.
template: kendo.template($("#matchesListViewTemplate").html())
});
$("#pager").kendoPager({
dataSource: dataSource,
autoBind: false
});
$(document).keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var searchTerm = $("#searchTerm").val().trim();
if (searchTerm.length < 1)
return;
dataSource.read();
dataSource.page(1); // makes another call to the remote service
}
});
Because data source is remote, when we call dataSource.page(1), kendo issues another call to the remote service. This behaviour is described in this so post:
If you are doing server side paging it should be enough doing grid.dataSource.page(1) since this will invoke the read exactly as you already realized.
What must I change so that after I search with new searchTerm, API call would be done only once and pager would go to page 1 without making another call?
I tried with dataSource.query() but still no luck? I hope I demonstrated enough.
Solution is to call dataSource.page(1) when dataSource.read() gets data / is done.
$(document).keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var searchTerm = $("#searchTerm").val().trim();
if (searchTerm.length < 1)
return;
dataSource.read().done(function() {
// in case remote service returns empty result set (but still http 200 code)
// page() makes another request (if data() is empty it makes another request)
// therefore we must check data length/total
if( dataSource.total() > 0)
dataSource.page(1);
}
});
If the read request's response have not arrived yet or if an error occurs, another read request is allowed (in order to fetch data). DataSource.read() makes asynchronously request and then dataSource.page(1) starts to execute. DataSource.page(1) function checks if there is any data read, if it's not it executes again read method - therefore we got 2 calls as you mentioned it. Because of asynchronously call this scenario may happen.

Extjs- Paging Toolbar Next Page and Previous Page Disable

I have three parameters startdate, enddate and name which I have to send to the server to get back Json response. I am displaying the response in a GridPanel.
My Ajax Request looks like this:
FilterOperSet: function(button){
var win = button.up('window');
var form = win.down('form');
var start = form.getForm().findField('startDate').getSubmitValue();
var end = form.getForm().findField('endDate').getSubmitValue();
var act = form.getForm().findField('actor').getSubmitValue();
Ext.Ajax.request({
url: 'ListData',
params: { type: 'recordedRequest', startDate: start,
endDate: end, actor: act, start:0,limit:10 },
success: function(response) {
var json = Ext.decode(response.responseText);
var mystore = Ext.data.StoreManager.lookup('RecordedRequestStore');
mystore.loadData(json.recordedRequests);
},
scope: this});
}
I have a button, when user enters values for startdate, enddate and name and clicks on the button the above listener sends them as parameters along with start and limit for paging and response is captured and stored in gridpanel.
My issue with paging toolbar is: I could see the following as response
recordedRequests
// has some meta data here
success
true
total
1339
But my paging tool bar show only one page and at bottom says 0 of 0 and to the right nothing to display. Infact it should say 1 of 14 and should allow me to go through next pages.
2) Also when I click on refresh button it calls my store and calls server, but i want to make a ajax request with startdate, enddate and name as parameters(which would be exactly what my button above listerner does)
My Store looks like this:
autoLoad: false,
remoteFilter: true,
buffered: false,
pageSize: 10,
//leadingBufferZone: 1000,
fields:['start', 'end', 'actor','serviceOp'],
proxy: {
type: 'ajax',
url: 'ListData',
store: 'RecordedRequestStore',
startParam:'start',
limitParam:'limit',
pageParam:'page',
reader: {
type: 'json',
root: 'recordedRequests',
successProperty: 'success',
totalProperty: 'total'
},
extraParams: {
'type': 'recordedRequest',
},
//sends single sort as multi parameter
simpleSortMode: true,
// Parameter name to send filtering information in
filterParam: 'query',
// The PHP script just use query=<whatever>
encodeFilters: function(filters) {
return filters[0].value;
}
},
listeners: {
filterchange: function(store, filters, options){
console.log( filters )
},
totalcountchange: function() {
console.log('update count: ')
//this.down('#status').update({count: store.getTotalCount()});
}
}
Any sort of help will of great value for me. Thanks in Advance.
Instead of Ajax Request. I should use
store.load(params{your params})
For nextpage and previouspage I used beforeload listener for custom parameters.

Wait for ajax requests in array to be completed

I'm trying to iterate through the ID's (containing an URL) of checked checkboxes. With each checkbox, it generates an AJAX-get which does a certain action on the database. This is working, however not all AJAX-gets seem to be executed (the redirect gets executed too fast).
As adviced, I've tried to make use of '$.when.apply', however, this doesn't seem to be working. I get a 'missing ) after argument list', most certainly generated in the part where I'm pushing the ajax-get.
Is this the right way or should I try another method?
$("#marksolved").click(function () {
var ajaxrequests = [];
// Loop through checkboxes.
$('input:checked').each(function () {
// Each id of a checkbox contains an URL.
var markurl = $(this).attr('id');
// Do the request.
ajaxrequests.push($.ajax({
method: 'GET',
url: markurl,
cache: false
});
});
// Check if all requests have completed.
$.when.apply($, ajaxrequests).then(function () {
// All requests have completed. An ajax-redirect will eventually take place too fast...
alert('All actions done!');
});
});
I get a 'missing ) after argument list', most certainly generated in the part where I'm pushing the ajax-get.
ajaxrequests.push($.ajax({
method: 'GET',
url: markurl,
cache: false
});
should be:
ajaxrequests.push($.ajax({
method: 'GET',
url: markurl,
cache: false
}));
It's missing a ), like the error says.
Side note: It would probably be far more efficient to combine all of your requests into one batch request instead of having one request for each checkbox.
You can use $.ajaxStop() to have an event raised when all ajax requests have ended, or $.ajaxComplete() for when all requests have completed.
try setting the ajax async option to false
$.ajax({
method:'GET',
url: markurl,
cache:false,
async: false
});
If you know how many ajax requests you are making, you could do something like this:
var ajax_count = 0;
var ajax_checker;
var ajax_n = 3;
$('input:checked').each(function() {
...
ajaxrequests.push($.ajax({
method:'GET',
url: markurl,
cache: false,
success: function(){ ajax_count++; }
});
}
// Check if all requests have completed.
function ajax_complete() {
if (ajax_count >= ajax_n) {
clearInterval(ajax_checker);
//continue working
alert('All actions done!');
}
}
ajax_checker = setInterval(function() {ajax_complete();}, 50);

How to abort remote Jquery Validator method upon submit

My site is http://www.extrabux.com/users/login
When a user is logging in, Jquery Validate plugin uses a "remote" function to check whether the provided email address exists in our database as a user. If the connection and our server is fast, the user sees feedback before she even finishes typing her password.
email: {
required: true,
email: true,
remote: {//http://docs.jquery.com/Plugins/Validation/Methods/remote
url: 'check-signin-email-address',
type: "post",
data: {
emailAddress: function() {
return $("#email").val();
}
}
}
}
If the connection or our server is slow, however, this causes an undesirable delay before the form can be submitted (because the Jquery Validate plugin waits until the form is confirmed to be valid).
What I'd like is:
If the remote query finishes before the user submits the form, it should block the submission (in the case where it finds that the email address is not in the database).
If the user submits the form before the remote query finishes, the remote query validation rule should be ignored (so that there is no delay--the server-side validation will catch that the user doesn't exist).
Thoughts?
function checkEmail(){
$("#email").removeClass('email'); // this stops validation during ajax
//might want to add a loading image to let user know
$.ajax({
type: //type
url: //url to check email,
data: //email to check,
success: function (msg) {
$("#email").addClass('email'); //turns validation back on
//take away loading image
if (msg.GoodEmail != "GoodEmail" ) { //however you check for existing email
$("#email").addClass('error'); //forces failed validation
}
}
});
}
This is an example using jquery's ajax , with this you can handle events before ajax , on success , on error , a little more control this way
I think I figured this out. Instead of using the "remote" option, I used addMethod to create a rule that I call "isExtrabuxMember". I also created some global variables and used ajax bound to the change of the #email field to check whether the provided email address belonged to any existing Extrabux member.
Please comment if this helps you or if you have better ideas.
I now have this above the "validate" plugin call:
jQuery.validator.addMethod("isExtrabuxMember", function(value, element) {
var emailRemoteFuncResult = checkSigninEmailAddressResult === null ? true : checkSigninEmailAddressResult;
return emailRemoteFuncResult;
});
var checkSigninEmailAddressResult = null;
var emailXhrCheck;
$('#email').bind('change keyup', function(){
checkSigninEmailAddressResult = null;
if(emailXhrCheck){
emailXhrCheck.abort();
}
emailXhrCheck = $.ajax({
url: '/users/check-signin-email-address',
type: "post",
async: true,
data: {
emailAddress: function() {
return $("#email").val();
}
},
success: function(data){
checkSigninEmailAddressResult = data;
$("#email").valid();
}
});
});
$('#loginForm').submit(function(){
if(emailXhrCheck){
emailXhrCheck.abort();
}
});
Then within the "validate" plugin call:
rules: {
email: {
required: true,
email: true,
isExtrabuxMember: true
},
password: {
required: true,
minlength: 4
}
},
messages: {
email: {
isExtrabuxMember: function(){
var currentEmail = $('#email').val();
return $.validator.format('<b>{0}<\/b> does not yet have an Extrabux account. <a href="\/users\/register?emailAddress={0}">Sign up?<\/a>', currentEmail);
}
},
password: {
required: "Oops, you forgot to enter your password!"
}
}

Resources