Redirect on Ajax Jquery Call Redirect on Ajax Jquery Call ajax ajax

Redirect on Ajax Jquery Call


JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){     jQuery.ajax({         type: "GET",         url: "populateData.htm",         dataType:"json",         data:"userId=SampleUser",         success:function(response){             if (response.redirect) {                window.location.href = response.redirect;            }            else {                // Process the expected results...            }        },      error: function(xhr, textStatus, errorThrown) {             alert('Error!  Status = ' + xhr.status);          }     }); }); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....        success:function(response){             if (response.getResponseHeader('REQUIRES_AUTH') === '1'){                 window.location.href = 'login.htm';             }            else {                // Process the expected results...            }        }//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.


For ExpressJs router:

router.post('/login', async(req, res) => {    return res.send({redirect: '/yoururl'});})

Client-side:

    success: function (response) {        if (response.redirect) {            window.location = response.redirect        }    },