I have the following code:
let selectedSub = $('#substation-select').val();
if (selectedSub == undefined) {
selectedSub = $('#substation-select option:first()').val();
}
loadAvailableAmbulances(selectedSub);
let selectedAmb = $('#ambulance-select').val();
if (selectedAmb == undefined) {
selectedAmb = $('#ambulance-select option:first()').val();
}
function loadAvailableAmbulances(selectedSub) {
$.ajax({
type: "GET",
data: {
substation: selectedSub
},
url: "/available-ambulances",
success: function(response) {
$('#ambulance-select').append(response);
}
});
}
What this piece of code does is actually generating the options for a select2. As you can see, I have an ajax request that triggers this function:
public function available_ambulances(Request $request)
{
$ambulances = Ambulance::whereHas('checklist', function($query) use($request) {
$query->where('used', 0);
$query->where('inventory_id', $request->substation);
})
->get();
$html = "";
foreach($ambulances as $ambulance) {
$html .= sprintf(
'<option value="%s">%s</option>',
$ambulance->id,
$ambulance->license_plate
);
}
return response($html, 200);
}
For some reason, in my jquery code, selectedAmb is null, even though I call the function loadAvailableAmbulances(selectedSub). It should get me the value of the first ambulance that is generated. Why is it returning null?