Reputation: 1302
I have an ajax form where I have defined some ajaxOptions
variable and pass that to Ajax.BeginForm
:
var ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
LoadingElementId = "loading",
OnBegin = "Base.loadingButton('#RegisterSubmit');",
OnSuccess = "Register.onSuccess",
OnFailure = "Base.onError"
};
All JavaScript functions are defined in a special namespace such as Base
, Register
,... .
Now when form submit and in server a error with Code: "0" and Type: "Sql" occurs and logged with elmah, and Status Code: "HTTP/1.1 302 Found" returned from server.
Question 1:
OnSuccess
function fired always even at this case which status 302 returned (but OnSuccess only must fire when status code is 200!!!),why?
Question 2:
sometimes OnSuccess
function never fire even status code is 200!!!,why?
Upvotes: 0
Views: 1374
Reputation: 1038710
Question 1: OnSuccess function fired always even at this case which status 302 returned(but OnSuccess only must fire when status code is 200!!!),why?
That's because when you perform an AJAX request to a server side script which redirects (status code 302), AJAX follows the redirect to the target location and eventually ends up with status code 200 => the OnSuccess will be fired because the request succeeds. There's not much you could do about it - it's how AJAX works - you cannot intercept 302 status code.
Are you using this to detect a redirect to the login page scenario? In case the session expires or something? The proper way to handle this scenario is to use 401 status code from the server and detect this event in the OnFailure
method. In order to prevent the FormsAuthentication module redirecting to the LogOn page but send 401 status code instead you may take a look at the following article
.
Question 2: sometimes OnSuccess function never fire even status code is 200!!!,why?
OnSuccess should always fire if the status code is 200, unless you have some javascript errors.
Upvotes: 4