Question

Is it possible to redirect a user to a different page/view and return a JSON result? I have a web application that makes a cross-domain call to another method on another asp.net mvc web app and I want to redirect the user to another page/view after they make the call, but I also want to return a JSON string to the calling web app indicating that the user was redirecting successfully or there was an error. How can I handle this scenario?

Is this something I can do in one method or does it need to be split up? If so, how?

Was it helpful?

Solution

This is all that you need for basic scenario:

$.ajax {
  ..
  ..
  ..
  success: function(data) {
    alert(data.message_for_user);
    // redirect from client
    window.location.replace(data.url_to_redirect);
    // or make another request to your server and redirect directly from server
    makeRequestToRedirectController(data.some_message_for_server)
  }
}

OTHER TIPS

If I understand correctly, you have three systems interacting here:

  • Client (HTML/JavaScript)
  • Server (ASP.NET)
  • Remote Server (technology used is immaterial)

And if I still understand correctly, the scenario is that Client is making a request to Remote Server, but Server needs to know the result of that request?

Since the request is between Client and Remote Server, Server isn't involved and can't directly receive a response from Remote Server. But Client can handle this interaction. One approach might be something like:

  • Client makes request to Remote Server
  • Client receives response from Remote Server, indicating either an error or to perform a redirect
  • If an error, Client notifies Server of the error (and probably notifies the user as well)
  • If a redirect, Client notifies Server of the success and then performs the redirect.

In mostly pseudo-code, that might end up looking something like this:

$.ajax({
    url: 'http://remoteserver/request_target'
}).done(function(data, textStatus, jqXHR) {

    // success, notify Server and redirect
    $.post('http://server/success_handler', successData)
     .done(function () {
        window.location.replace('http://remoteserver/redirect_target');
    });

}).fail(function(jqXHR, textStatus, errorThrown) {

    // fail, notify Server
    $.post('http://server/error_handler', errorData);

});

So first it's performing an AJAX request to Remote Server. If the request succeeds, it then performs an AJAX request to Server to notify of the success and then, after that request, performs the redirect. If the request to Remote Server fails, if performs an AJAX request to Server to notify of the error. (What goes in successData or errorData, if anything at all, is up to whatever you need to send to Server.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top