Call Response.redirect via Ajax

I am making an Ajax request as follows:

$(".box01 .selproduct").live("click", function(e) { var color = $(this).parent('.box01').find('.color').val(); var size = $(this).parent('.box01').find('.size').val(); var pid=$(this).parent('.box01').find('.hdinput').val(); var pathname = window.location.pathname; var data = { submit: "selected",size:size,color:color,pid: pid}; $.ajax({ type: "POST", url: pathname, data: data, success: function(data) { }, error: function(XMLHttpRequest, textStatus, errorThrown) { }, complete: function(data) { } }); return false; }); 

And on the server side, I made this code:

  if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["pid"])) { var path = HttpContext.Current.Request.Url.AbsolutePath; HttpContext.Current.Response.Redirect(path); } 

Ajax POST works great. I can see in the Web Developer Tools in mozilla, but the page is not redirected to another page, as I expected. Can someone tell me what I am doing wrong?

Or is it impossible to call Response.Redirect via Ajax?

+7
jquery ajax
source share
2 answers

Yes, as far as I know, you cannot just detect client-side redirection. Remember the following answers:

  • Redirect detection in jQuery $ .ajax?
  • Returning a redirect in response to an XHR request

One thing you can do is return something that indicates a redirect from your server code. Something like the following JSON:

 { success: true, redirect: true, redirectURL = "http://something.com/path/to/good/stuff" } 

How you achieve the above in your server code is up to you.

Then in your client code you can do the following:

  $.ajax({ type: "POST", url: pathname, data: data, success: function(data) { if(data.redirect) { window.location = data.redirectURL; } }, 
+11
source share

Cannot call Response.Redirect in WebMethod. You can use instead

  success: function(data) { window.location.href="path.aspx"; } 

in ajax success function.

If the page name is dynamic in nature, return pagename from the web method and use it to redirect the page.

+5
source share

All Articles