I am facing a problem.I have multiple form submission in one page. I need to submit all of those with out page reload. I am try with some Ajax code. with ajax code, first form are submit properly but rest of form is not working.
here is my view file
<div class="col-md-6 col-lg-6 col-sm-6 col-lg-offset-5">
@foreach($questions as $question)
<form method="post" action="{{route('answer.store')}}" id="ansform">
{{ csrf_field() }}
<h1>{{$question->question}} ?</h1>
<div class="col-lg-offset-1">
<input type="hidden" name="question" value="{{$question->question}}">
<input type="hidden" name="student_id" value="{{$student_id}}">
<input type="hidden" name="true_answer" value="{{$question->answer}}">
<input name="answer" value="{{$question->choice1}}" type="radio"> {{$question->choice1}} <br>
<input name="answer" value="{{$question->choice2}}" type="radio">{{$question->choice2}}<br>
<input name="answer" value="{{$question->choice3}}" type="radio">{{$question->choice3}}<br>
<input name="answer" value="{{$question->choice4}}" type="radio">{{$question->choice4}}<br>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</div>
</form>
@endforeach
Output of view file is-
My route Answer.store is here
public function store(Request $request)
{
//
if ($request->ajax()) {
$answer=Answer::create([
'stu_id' => $request->input('student_id'),
'question' => $request->input('question'),
'given_answer' => $request->input('answer'),
'true_answer' => $request->input('true_answer')
]);
return response($answer);
}else{
return "ajax not done";
}
}
And finally ajax script is
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$('#ansform').on('submit',function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type : post,
url : url,
data :data,
success:function(data){
console.log(data)
}
})
})
</script>
Anyone please help me. How can I do this?

$('.someclass').on('submit',function(e){)<form method="post" action="{{route('answer.store')}}" id="ansform">and$('#ansform').on('submit',function(e){use<form method="post" action="{{route('answer.store')}}" class="ansform">and$('.ansform').on('submit',function(e){