Time out Ajax requests with jquery? - c#

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
}
}
);

Related

Check is aspx session expired via jquery ajax request

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">

Sending $ajax via jQuery to C# codebehind not working

I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?
[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})
If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)

What happens to an ASP.NET MVC controller when the user navigates away before a response is received?

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.

Call C# function from Javascript in aspx webform and then reload page

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.

how to get Asynchronous response to an Ajax request? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
ASP.NET Server does not process pages asynchronously
There is a question regarding Asynchronous response to an Ajax request.
I’m working on a web application to enable some simple image processing actions for user, using ASP.Net + Ajax. As most of image processing actions takes a while to accomplish, we’d like to utilize user to send the request to the server through Ajax, and get the partial response immediately, while the server is processing and to send completed response in a later time (i.e. 10/20 seconds later for instance).
This way, I suppose the server should be able to push the late response (which obtained 10/20 seconds later) to the client.
Is there any idea how to realize such interaction?
The closest thing you'll get is JSONP, which can be used with jQuery.
like:
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/tags/ravendb/wikis',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
jsonp: 'jsonp'
async: true,
success: function (data) {
if (data.tag_wikis.length > 0) {
alert(data.tag_wikis[0].wiki_excerpt);
}
},
});

Categories