Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Response.redirect through Ajax

I am making an Ajax request like this:

 $(".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 in the server side I have done some code like this:

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

Ajax POST works fine. I can see in Web Developer Tools in mozilla but page is not redirected to other page as I supposed. Can any one tell me what I am doing wrong?

Or Is it not possible to call Response.Redirect through Ajax?

like image 489
None Avatar asked Nov 04 '13 06:11

None


People also ask

How do I redirect a page in ajax?

How do I redirect to another view in ajax success? $. ajax({ type: 'POST', url: 'AJAX URL', data: “YOUR DATA” // don't forget to pass your csrf_token when using post success: function(data){ $(“what_ever_you_want_to_replace”). html(data.

Does ajax follow redirect?

ajax appears to always follow redirects.

Do ajax calls send cookies?

Basically, ajax request as well as synchronous request sends your document cookies automatically.


1 Answers

Yeah, to my knowledge you can't simply detect the redirect from the client-side. Reference other answers like these:

  • Detecting a redirect in jQuery $.ajax?
  • Returning redirect as response to XHR request

One thing you can do is how return something that indicates a redirect from your server-side 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-side code is up to you.

Then in your client-side code you can do the following:

  $.ajax({
    type: "POST",
    url: pathname,
    data: data,
    success: function(data) {
      if(data.redirect) {
        window.location = data.redirectURL;
      }
    },
like image 139
Patrick Jones Avatar answered Sep 19 '22 03:09

Patrick Jones