How to send ajax request to check session timeout and render relogin message in grails? - ajax

I want to display a message to the user saying, "you're logged out re-login please!" when session is timed-out, sending an ajax request each time. If session timer ends i want to send final ajax request displaying above message. But the problem here is i don't know where should i have to keep my ajax and jquery codes and since i don't have much knowledge about ajax request, can anyone explain this process with codes. In siple my requirement is like of what facebook shows on session time out, or when any one tab in case of multiople tabs are logged out. I'm working on grails project.

Do your ajax request like this
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
success: function(data) {
// do procedure if success
}
error : function(xhr, type, error){
// do procedure if fail
// may be send a message to the server side to display a message that shows session timeout
}
});
Handle your session timeout in the error function

I did it myself and this is the js code for it "gracefulSession.js" and call this javascript at the page where you are going to embed your html code..
function checkSessionStatus() {
var lStorage = getLocalStorage();
if (lStorage) {
//lStorage.setItem('poleTime',new Date());
var poleTime = lStorage.getItem("poleTime");
var parsedTime;
try {
parsedTime = new Date(poleTime);
} catch (e) {}
//alert(new Date()-parsedTime)
//alert(new Date())
//alert(parsedTime)
//3900000 = 1H5M
if (parsedTime && (new Date() - parsedTime) < 3900000) {
//alert('NCATCH'+parsedTime);
} else {
//alert('POINT');
poleSessionStatus();
}
}
}
function setlatestPoleTIme() {
//alert("SETTING POLE TIME");
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('poleTime', new Date());
}
}
function setCheckSessionTimer() {
var lStorage = getLocalStorage();
var isLoggedOut = false;
if (lStorage) {
if (lStorage.getItem('isLoggedOut') == 'true') {
isLoggedOut = true;
}
}
//console.log('checkingIfLoggedOut');
if (!isLoggedOut) {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("NOPT LO");
$('#LoggedoutMessage').hide();
checkSessionStatus();
} else {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("KO");
//alert("You're Logged Out from other tab");
$('#LoggedoutMessage').show();
}
}
function logout() {
//alert("LOGGIN OUT")
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('isLoggedOut', 'true');
}
}
function resetLoggedOutFLag() {
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.removeItem('isLoggedOut');
}
}
function getLocalStorage() {
var storage, fail, uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (e) {}
return storage
}
Now, HTML code to embed ,
<div id="LoggedoutMessage" style="display:none;position:absolute;background:black;height: 200%;width:100%;top: 0;z-index: 10000;opacity: 0.9;">
<div id="login_box" style="position:fixed;left:38%;top:30%; padding:10px; width: 365px;margin: 0 auto;border: 0px solid #CCC;margin-top: 35px;height: 150px;background: white; border-radius:3px;">
<div id="login_title">
<h1>You have been logged out.</h1>
</div>
<div id="reLogin">
<p>Please login to continue.</p>
<g:link controller="dashBoard" action="index" target="_blank" onclick="logout();">Login</g:link>
</div>
</div>
</div>
Finally where you keep your html,keep this javascript code at top of it embedding script tag:
function poleSessionStatus() {
jQuery.ajax({
type: 'POST',
data: '',
url: '<g:createLink action="ajaxCheckSession" controller="dashBoard"/>',
success: function (data, textStatus) {
//setTimeout ( "checkSession();", 5000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#LoggedoutMessage').show();
},
complete: function (XMLHttpRequest, textStatus) {
$.unblockUI();
}
});
}

Related

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

Routing through AJAX

I have an ajax request handling validation of form fields (login+signup+forget password). In its success scenario, I want it to route to another page, but when I use Redirect::route('name'); as return from controller, it completes the request with 200 and generates another GET request which just returns the html as response and does not route to other page.
AJAX
$('form[data-remote]').on('submit', function (e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
beforeSend: function () {
$('#ajax-loading').show();
$(".has-error").text("");
$('#login-error').addClass('display-hide');
$('#forget-user-error').addClass('display-hide');
}
})
.done(function (data) {
if (data.signup_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.email_fail) {
$('#email_error').text('This Email already in use against an account.');
}
else if (data.company_fail) {
$('#email-error-popup').trigger('click');
}
else if (data.login_fail) {
$('#login-error').removeClass('display-hide');
}
else if (data.forget_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});
How can I route to the other page on success condition? The ajax is triggered on a form submit button.
As you are doing an ajax request you can't just redirect from the controller on successful validation. Instead, just return the url you want to redirect to, as response to the ajax request similar to the way you are returning the validation errors. And in your js file use that url to redirect to new page.
#your above code
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else{
window.location.replace(data.redirect_url); //this will redirect to new page
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

mvc3 ajax submission on the controller side. How?

I don't understand once button clicked
How to handle ajax call on the server side so that my DataAnnotation work
and I get success or error message.
<script src="../../../../Content/Scripts/jquery-1.4.4-vsdoc.js" type="text/javascript"></script
<script type="text/javascript">
$(function ()
{
$("#createButton").click(function ()
{
var profile = {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val()
};
$.ajax({
url: "/Profile/Create",
type: "Post",
data: JSON.stringyfy(profile),
dataType: "json",
contentType: "Application/json; charset=utf-8",
success: function () {
$("#message").html("Profile Saved.");
},
error: function () {
$("#message").html("Error occured");
}
});
return false;
});
});
</script>
//Server side
public ActionResult Create(string confirmButton, CreateViewModel userVm)
{
if (confirmButton != "Create Profile") return RedirectToAction("Index");
if (!ModelState.IsValid)
return View("Create", userVm);
User user = new User();
Mapper.Map(userVm, user);
_repository.Create(user);
return RedirectToAction("Details", new { id = user.UserId });
}
If I remember correctly (it's been a while since I played with jquery), the success and error are indicative of the return value of the actual HTTP request itself. For example, if you hit a 404, you'd get an error message.
Regardless of whether or not a profile was created successfully through your page logic, if the request itself was processed, then the success message will be hit - you need to interpret the return value yourself at that point.
Try returning a JsorResult in place of redirecting to a view, then client side, parse the JsonResult and act accordingly.
[HttpPost]
public JsonResult DeleteDoc(int Id, int DocCode, SomeObject Model)
{
try
{
// Check annotations stuffs
if (!Model.IsValid) {
var jsonDataM = new { ExitCode= -100, message = "Invalid Model" };
return Json(jsonDataM, JsonRequestBehavior.DenyGet);
}
// My logic in here
var jsonData = new { ExitCode= 0, message = "Everything's ok" };
return Json(jsonData, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
var jsonData2 = new { ExitCode= -1, message = "Everything's Ko" + e.Message };
return Json(jsonDat2a, JsonRequestBehavior.DenyGet);
}
}
in the OnSuccess callback you can refer to this with:
<script type="text/javascript">
function MyAjaxCallBack(context) {
var code = context.ExitCode;
if (code != 0) {
alert (context.message);
}
}
</script>
Please note that this code is simplified. When managing the IsValid on Model, I usually iterate del ModelState in order to build up a message.

Resources