I use asp.net to manage the session state of my site. I also use jquery and $.ajax(...) for synchronous and asynchronous requests.
Normally, in asp.net if a users session times out, it can be detected via a full or partial post-back. However, suppose a partial or full-post-back does not occur because I am using jquery ajax calls to a static c# web method. Whats the best what to know if the session timeout?
i would create a javascript interval to make a ajax request from time to time, something like this:
<script>
$(document).ready(function () {
setInterval(function (){
$.ajax({
url: 'WebMethodhere',
type: 'GET',
success: function (result) {
if(result!='true')
{
//It means that the Session expired, so do somethig
}
}
})
},3000);
});
</script>
I used 3000ms in this example, but the time it's up to you.
And your webmethod could be really simple:
if(Session["WhateverSession"]==null)
{
return false;
}
else
{
return true;
}
There are couple of approaches to achieve it.
Approach #1: Create a generic handler and implement the IReadOnlySessionStateinterface to access session variables from this handler. Use a ajax get request and access this generic handler which provides whether session is active or not.
Approach #2: Decorate a public method of your page with [WebMethod] (using System.Web.Services) and access this method through ajax get request which provides whether session is active or not.
But all these approaches should be used just to check session is active or expired. But if the session is active, it'll renew your session - it may not be desirable. Please check that option also.
The easiest solution was to force a post back at certain intervals.
<meta http-equiv="refresh" content="1800">
Related
I have an AJAX action that can take a couple of minutes to complete depending upon the amount of data involved. If a user gets frustrated and navigates away while this action is still running, what happens to the controller? Does it complete anyway? Does it know the request should be abandoned and dispose of the controller object?
It will not cancel the request to the server as the act of navigating away does not send any information back to the server regarding that request. The client (browser), however, will stop listening for it. After the request finishes, regardless if the client was listening for it or not, the controller will dispose as it typically would.
With that said, you could get fancy and use a combination of listening for a page change on the client side and calling abort on the AJAX request to the server.
This SO question discusses how to abort a request. I could imagine setting a variable when you first start the AJAX request and then unsetting it when it finished.
Warning - Pseudo code below
var isProcessing = false;
var xhr = $.ajax({
type: "POST",
url: "myUrl",
beforeSend: function(){
isProcessing = true;
}
complete: function(){
isProcessing = false;
}
});
window.onbeforeunload = function(){
if(isProcessing){
xhr.abort();
}
}
The above is very basic idea of the concept, but there should probably be some checks around if the xhr object exists, perhaps also bind/unbind the window.onbeforeunload in the beforeSend and complete object handlers for the .ajax() item.
Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.
I need to run a specific javascript function only when the page is submitted using ajax.
I've tried the following:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
But it seems to run during normal post-backs as well. I've also tried replacing the Page object with the UpdatePanel control but without any difference.
Is it perhaps possible inside the javascript function MyFunction() to detect if it is an ajax or normal submit?
You can utilize Sys.WebForm.PageRequestManager two events
1) add_initializeRequest --> When an ajax post back is initiated
2) add_endRequest --> when an ajax post back is finished.
PageRequestManager also provides a function "get_isInAsyncPostBack()" which tells that if page is still in process of an existing ajax postback.
Example:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Only one async request at a time
if (prm.get_isInAsyncPostBack()) {
prm.abortPostBack();
}
//Call the function or process you want to perform on ajax request begin
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
//Call the fucntion or process you want to perform on ajax request end
});
Any question, feel free to ask
This code solved the problem. Thanks to #user1341446 for pointing me in the right direction.
Register the javascript function on submit:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
Inside the function detect if ajax submit:
function MyFunction()
{
var isAjaxSubmit = false;
if (typeof (Sys) != "undefined")
isAjaxSubmit =
Sys.WebForms.PageRequestManager.getInstance()._postBackSettings.async;
}
I think that you can set like on post and get methods in jquery timeouts but I am wondering does jquery have a global timeone like it has with ajax start and stop.
Like I would like to set it that if say a post or get or some sort of ajax request is running and it runs more then X amount of seconds. That a popup or something in that nature comes up saying that the "server is slow and the request has timed out" and kills that request.
Then the user can either try again or do something else.
Does jquery have something like this?
Thanks
The jQuery.ajax function is what you want. It gives you access to a pretty large set of options for making AJAX calls.
Specifically, you're going to want to make a call similar to
$.ajax({'complete': callbackFunction, 'url': 'foo/bar/', 'timeout': 5000, 'error': errorCallback});
The two options you're interested in are timeout and error. The entire documentation for the function is here. It's a bit more work than using the more standard get/post functions, but much more flexible.
The error function is very similar to the standard callback you use with any jQuery AJAX request. While the callback is called if the request succeeds, the error function is called when it fails (such as 404 errors, or when the timeout is hit). You'd use the error function to display your message to the user that their request has timed out. Full documentation on the function's arguments (which practically speaking, you probably won't need to use) is available on the $.ajax doc page (linked earlier).
Alternatively, you can set the timout globally on every AJAX call by using the jQuery.ajaxSetup function. Its arguments are exactly the same as the jQuery.ajax function, so you'd do something like this:
$.ajaxSetup({'timeout': 5000, 'error': errorCallback});
The upside is that you can continue using jQuery.get/jQuery.post, but the downside is that you have to do extra work to make AJAX calls without a timeout.
Yep, jQuery has a 'timeout' property (in milliseconds) you send the $.ajax() event:
http://www.bennadel.com/blog/1500-Catching-Timeout-Errors-With-jQuery-Powered-AJAX.htm
$.ajax(
{
method: "get",
url: "yourpage.php",
dataType: "json",
timeout: (3 * 1000), // 3 seconds
success: function(){
//success code here
},
error: function( request, strError ){
//error code here
}
}
);
I'm trying to find an answer for a problem my developers are having. I don't know this well enough myself...
We are using ASP.NET with C#.
When a user presses a button on a page, we call a hander to save the session variables to the current view state of the form (some IDs that are used).
Then, we call a GreyBox window with other functionality.
Because this is asynchronous, greybox doesn't wait for the handler to respond.
In many cases the greybox is loaded before the session variables are saved to the view state, and in this case, grey box doesn't have the IDs that are necessary.
On the localhost, it is fast enough that we never realized the problem. In production, it is a problem.
What would be the correct solution here?
The asynchronous call to the server to save the session will return a response to the client. Don't start greybox until you have a successful reply from the server. If there is only one thing causing async postbacks on your form, then you can plug into the reply by doing this:
<script type="text/javascript">
//<![CDATA[
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endRequest);
function endRequest(sender, e) {
// Do stuff
}
//]]>
</script>
For more complicated scenarios see the article on MSDN on this subject.
You need to make sure that you're additional code is running in a callback method from your AJAX request.
If you're manually calling a web service or page method the Sys.Net.WebServiceProxy.invoke method takes a callback: http://msdn.microsoft.com/en-au/library/bb383814.aspx
I have a feeling that the PageRequestManager which David suggested only works if you are using an UpdatePanel to perform the AJAX request.