Johan
Johan

Reputation: 35213

Redirect from .ashx to .aspx using $.ajax()

If I use the solution posted here, I won't get transferred to the new page. But if i inspect the $.ajax() call in the console, the actual .aspx page seems to be in the response body. So my guess is that the .ashx gets redirected to the .aspx.

void ProcessRequest(HttpContext context)
{
     context.Response.Redirect(newUrl);
}

How do I redirect the user from the .aspx page that sends the ajax request? Do I need to call a method on that .aspx from my handler.ashx?

Upvotes: 1

Views: 1976

Answers (1)

Aristos
Aristos

Reputation: 66641

The Response.Redirect command is nothing more than instructions to the browser to move to some other page. This commands are first a header instruction to the browser. Also there is a javascript small script that is written on the page in case the header is fail.

Now, when you make the call with Ajax (no matter if its handler or page) the results return to the page but inside the ajax buffer, the redirect headers are "eaten" and not go to the browser itself to runs them. So no redirect can be directly done via ajax call.

What you should do, is to return a signal to your ajax call, and see that signal/flag and make the redirect using javascript call window.location.replace("redirectPage.aspx")

For example, something like:

$.ajax({
    url: "action.ashx",
    type: "GET",
    dataType: 'json',
    success: function(data)     
    {
        if(data.NeedRedirect)
            window.location.replace("WhereToMove.aspx");
    },
    error: function(responseText, textStatus, XMLHttpRequest) 
    {
        window.location.replace("WhereToMove.aspx");
    }
});

Upvotes: 1

Related Questions