views:

444

answers:

4

Hi, I'm trying to post with JQuery like this:

$.post("NiceController/Create/", { field1: data1, field2: data2 },
function(data, textStatus) {
    if (data.Status)
        //Do something
}, "json");

The problem is, that when I'm not authenticated I don't get redirected, to log-on page, because it's not a full form submit. Question is: How do I, programmatically, know that I'm not authenticated and should redirect to log-on page?

A: 

You could do something like:

$.post("NiceController/Create/", { field1: data1, field2: data2 },
    function(data, textStatus) {
        if (data.Status)
            if(data.Status == 'authFailed') {
                window.location.href = '/login';
            }
        }
    }, "json");
karim79
problem is, I don't get to the resulting function. firebug shows, that there is GET request to logon happening, but it's probably inside js, or something, because page itself doesn't get refreshed.
Dale
+1  A: 

I don't know if there's a more official answer, but can you $.get('NiceController/AmILoggedIn') first? Then, depending on the response in there, $.post or do some kind of redirect through a login page?

Dan F
yes, that is one solution, thanks. i wonder, if i still can do it in one request somehow.
Dale
+1  A: 

If you use the ajax method, you should be able to add an error handling function. I believe that since you are asking for JSON, a parseerror ought to be returned since what you will be getting back is a redirect, not JSON. You might also be able to get the same effect using an global ajaxError handler and continuing to use post.

tvanfosson
+1  A: 

I assume your NiceController/Create/ redirects to the login page, and that is what you're seeing. Instead of a nice status, you get back a bunch of HTML from the login page.

You have 2 options: remove the Authorize attribute from the Create action, and handle it internally, e.g. by returning a JSON error message.

Or: check first whether you are logged in, and then call the Create action only when the user is logged in

chris166
I think the best way is to handle it internally, thanks.
Dale