I am trying to figure this out. I have backend in laravel and i am returning id of new created client. How can i use this param in js redirect? This is my best try but i am getting into this url: client/%27+response.id+%27 it should be client/15
$.ajax({
method: "POST",
url: '{{ route('add-new-client') }}',
data: {
shop_name: shop_name
},
success: function(response) {
console.log(response);
$("#addClientModal").modal("hide");
// Přesměrování na URL s předáním nového id
window.location.href = '{{ route("client", ["id" => "' + response.id + '"]) }}';
},
error: function(error) {
console.error(error);
}
});
Solution in PHP, after a while my patience run out and i come up with this idea, i just return whole url created in laravel. Works like a charm
public function xxx(Request $request)
{
.... code ....
return response()->json([
'url' => url(action([ClientController::class, 'index'], ['id' => $shop->id])),
'success' => 'Shop byl úspěšně vytvořen.'
]);
}
Everything inside {{ ... }}
is evaluated in php.
Hence nothing from JS land is available inside it (including the response) and thats why id
for the route is being evaluated as a literal string.
You can test this in a url decoder where %27+response.id+%27
becomes '+response.id+'
Your options are:
Send the redirect url as part of the response after creating the entity (as you are doing for a workaround). This is a good strategy as the FE can remain "dumb"
set the redirect url directly. This is a very common but slightly brittle approach
window.location.href = '/client/' + response.id