Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

VanKarma's avatar

Redirect to a route via javascript

I am validating a user if it's logged in or not from javascript to route. When a user is logged in, I check if the user has the details saved in the Shipping model.

If it is existing, it should redirect to my market.store route. If not, then it should return a json response.

I am getting the json responses correcly, however when the user is authenticated and the details aren't set in the Shipping model, it doesn't redirect the user to the market.store route.

Here's my JS:

$("#checkout").click(function(e){
    $.ajax({
        url: '/checkout',
        method: 'POST',
        data: {test : 'data'},
    }).done(function(data){
        console.log(data);
        if(data.message.includes('NRA')){
            $('#shipping').modal();
        }else if(data.message.includes('S')){
            $('#shipping').modal();
        }else{
            
        }
    })
});

Also, here's my controller:

public function validateCheckout(){
    $check = \Auth::check();
    if($check){
        if(Shipping::where('user_id', \Auth::user()->id)->exists()){
            return response()->json(['message' => 'HRA']); 
            // Has record and authenticated - HRA
            return redirect()->route('ship.store');
        }else{
            return response()->json(['message' => 'NRA']); 
            // No record but authenticated - NRA
        }
    }else{
        return response()->json(['message' => 'S']); // Session only - S
    }
}

Sorry for the long code. I don't know which is better, to redirect the user from controller or through JS.

PS: the JS file is inside the resources folder

0 likes
2 replies
fylzero's avatar

@vankarma Redirect on the backend won't do anything if you're calling via ajax.

In the ajax success response you'll have to redirect from the client side.

Put the following somewhere inside your ajax done closure.

window.location.href = 'http://wherever.com/someroute';
24 likes
Sinnbeck's avatar

You cannot redirect an ajax request in laravel. You need to do it in Javascript

window.location.href = "http://newurl.com";

Please or to participate in this conversation.