Is it possible to send error or success messages through AJAX without clicking a submit button in a form, especially if there is no form present?
In my Laravel project, I have implemented a method where upon form submission, the data goes to a controller (using the form's action attribute). Inside the controller function, it can return a view with data and refresh the page to display error/success messages. For example:
return redirect()->back()->with('success', 'Successfully Added!');
However, I would like the same functionality to occur when clicking a button without a form. I tried adding an onclick event to the button, which triggers a JavaScript function to call the controller via AJAX. But after this call, the above code doesn't work as expected. No errors are thrown either.
<button type="button" onclick="submit()" class="btn btn-primary"
>Submit</button>
<script>
//when click submit button
function submit(){
var _token = $('input[name="_token"]').val();
$.ajax({
url: "{{ route('RecipeController.submit') }}",
type: "POST",
data: { _token:_token
}
})
}
</script>
Does anyone have a solution for this issue?
Below, you will find message code examples that may be helpful:
@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