can someone help me with the code I made?, my radio button can't automatically save data with ajax jquery in laravel 8 and I don't get an error message
my controller : Q_AnswersController
public function storeAns(Request $request)
{
$model = new Q_Answer;
$model->user_id = Auth::id();
$model->topic_id = $request->topic_id;
$model->question_id = $request->question_id;
$model->user_answer = $request->radio_ans;
$model->answer = $request->answer;
$topik = $request->topic_id;
$model->save();
return redirect('qanswers/'. $topik);
}
this my route :
Route::post('/storeAns',[Q_AnswersController::class, 'storeAns'])->name('storeAns');
this is my blade :
@foreach ($datas as $key=>$value)
<p>{{ $value->question }}</p>
<p><input type="radio" id="radio1" name="radio_ans" value="{{ $value->a }}"><label> {{ $value->a }}</label></p>
<p><input type="radio" id="radio2" name="radio_ans" value="{{ $value->b }}"><label> {{ $value->b }}</label></p>
<p><input type="radio" id="radio3" name="radio_ans" value="{{ $value->c }}"><label> {{ $value->c }}</label></p>
<p><input type="radio" id="radio4" name="radio_ans" value="{{ $value->d }}"><label> {{ $value->d }}</label></p>
<p><input type="radio" id="radio5" name="radio_ans" value="{{ $value->e }}"><label> {{ $value->e }}</label></p>
<p><input type="radio" id="radio6" name="radio_ans" value="{{ $value->f }}"><label> {{ $value->f }}</label></p>
<input type="hidden" name="topic_id" readonly value="{{ $value->topic_id }}">
<input type="hidden" name="answer" readonly value="{{ $value->answer }}">
<input type="hidden" name="id" readonly value="{{ $value->id }}">
<input type="hidden" name="question_id" readonly value="{{ $datas->currentPage() }}">
<input type="hidden" name="user_id" hidden readonly value=" {{ Auth::id(); }} " >
@endforeach
this is my script :
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var user_id = $("#user_id").val();
var topic_id = $("#topic_id").val();
var question_id = $("answer").val();
var answer = $("answer").val();
var user_answer = $("radio_ans").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{ url('qanswers.storeAns') }}",
method: "POST",
data:{
user_id:user_id,
topic_id:topic_id,
question_id:question_id,
answer:answer,
user_answer:user_answer
} ,
success: function(data) {
$('#alert').text('Data Inserted Successfully..');
}
});
});
});
I really appreciate if you guys can help, thank you
CodePudding user response:
you get radio button value using radio button name in jquery but this syntax give value undifined
var user_answer = $("radio_ans").val();
you can try this -
var user_answer = $("input[name=radio_ans]:checked").val();
CodePudding user response:
You are sending user_answer key in your ajax request and in the backend, reading $request->radio_ans instead of $request->user_answer. so change this line:
$model->user_answer = $request->radio_ans;
to
$model->user_answer = $request->user_answer;