I'm trying to implement Ajax call in Laravel project. Currently I'm looking for a way to display success/error messages after Ajax successfully execute something & redirect the page. In Laravel controller, usually I can do it like this:
if($patient->wasRecentlyCreated){
return redirect('/patients')->with('success','New patient data saved');
} else {
return redirect('/patients')->with('error','Patient already exist');
}
As in the blade view, I have added the message section in the layout page (so that the message will appear on the top of redirected page) :
@if(count($errors)>0)
@foreach ($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
@endforeach
@endif
@if(session('success'))
<div class="alert alert-success">
{{session('success')}}
</div>
@endif
@if(session('error'))
<div class="alert alert-danger">
{{session('error')}}
</div>
@endif
The case with Ajax call, I'm able to pass the redirect target URL from Laravel controller but I don't know how to pass the success/error message to Ajax. Below is the sample of Laravel controller I have made to handle the Ajax:
if($settlement->wasRecentlyCreated){
return url('/patients');
}
And in Ajax section, I can redirect using window.location :
$.ajax({
url: "/createsettlement",
type: 'post',
data: {
billing_id : billing_id,
prices : prices,
_token : '{{csrf_token()}}'
},
success: function (data) {
console.log(data);
window.location = data;
},
Any idea how to pass the success/error messages while Ajax do page redirection?