What is your question?
Nov 29, 2017
8
Level 4
Stopping the form from refreshing after submit , jquery, ajax and Laravel
I don't want to refresh page after click submit form! it is from my blade....
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModal">
Report this
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Report this</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{route('report')}}" method="post">
{{csrf_field()}}
<input type="hidden" name="id" value="{{$row->id}}">
<input type="text" name="des" placeholder="I report this quiz because" class="form-control">
<button type="submit" id="tes" class="btn btn-primary btn-round btn-md">Submit</button>
</form>
</div>
</div>
</div>
</div>
It is from controller....
public function report(Request $request){
$data=$request->validate(['des'=>'required']);
$id=$request->id;
$report=Question::findOrFail($id);
$uid=\Auth::id();
Report::create([
'question_id'=>$id,
'user_id'=>$uid,
'des'=>$data['des']
]);
return redirect()->back();
}
Level 40
Add an ID to your form to make it easy to grab in jQuery: <form id="report" action="{{route('report')}}" method="post">
Then you can a bit of jQuery to trap the submit event, prevent the HTML submission (which would cause a refresh), and then send along the input data using AJAX:
<script>
$(function () {
$('#report').submit(function (e) {
e.preventDefault() // prevent the form from 'submitting'
var url = e.target.action // get the target
var formData = $(this).serialize() // get form data
$.post(url, formData, function (response) { // send; response.data will be what is returned
alert('report sent')
})
})
})
</script>
Please or to participate in this conversation.