Exception or error:
I have two tables: role and persons.
In my persons table I have the foreign key ‘idrole’ of the table: role. I created a drop-down list which retrieves the roles from my table: role
My problem is as follows: I can’t get the id of the selected role from the drop-down list
I am a beginner with laravel and ajax. Thank you for your help
Code of my html page :
<span>Name Role: </span>
<select style="width: 200px" class="namerole" id="nom">
<option value="0" disabled="true" selected="true">-Select-</option>
@foreach($roles as $role)
<option value="{{$role->nom}}">{{$role->nom}}</option>
@endforeach
</select>
<span>Id Role: </span>
<input type="text" class="idrole" id="idrole" disabled>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '.namerole', function () {
var role_nom = $(this).val();
var div = $(this).parent();
$.ajax({
type: 'get',
url: '{!!URL::to('findIdRole')!!}',
data: {'nom':role_nom},
dataType:'json',
success: function (data) {
console.log('success');
div.find('.idrole').val(data.id_r);
console.log('error');
}
});
});
});
</script>
My function:
public function findIdRole(Request $request){
$rj=DB::table('role')
->select('id_r')
->where('nom',$request->nom)
->first();
return response()->json($rj);
}
How to solve:
use$ request->get(‘nom’) instead of $request->nom ,
i am not sure but probably it is coming as array and also not an object
public function findIdRole(Request $request){
$rj=DB::table('role')
->select('id_r')
->where('nom',$request->get('nom')) // here is the change
->first();
return response()->json($rj);
}