I have a form in Laravel where I use Ajax to dynamically create options in the selects, based on previous filled information. I am very new to Ajax, so maybe I understand the concept wrong.
Below the first select, just based on a "regular" query.
<select id="selectCompany" name="companyId">
@foreach($companies as $company)
<option value="{{ $company->id }}">{{ $company->name }}</option>
@endforeach
</select>
Based on the first selected value, I use Ajax to select options for the next selection field.
$(document).ready(function () {
$('#step1').on('click', function (fetchLocations) {
$.ajax({
type: 'GET',
url: '/get/info/',
dataType: 'json',
data: {
companyId: $('#selectCompany option:selected').val()
},
success: function (response) {
$('#selectLocations').empty();
$.each(response.locations, function (key, value) {
$('#selectLocations').append('<option value=' + key.id + '>' + value.title + '</option>');
});
},
error: function (ts) {
alert(ts.responseText);
}
});
});
I add the options to the following select
<select id="selectLocations" name="locationId">
</select>
Now I want to submit the form via normal Laravel route, unfortunately the value send from the second select is "Undefined". How can I fix this?
Laravel Request parameters:
The problem is with this line:
$('#selectLocations').append('<option value=' + key.id + '>' + value.title + '</option>');
The short answer is that key.id
should be value.id
like this:
$('#selectLocations').append('<option value=' + value.id + '>' + value.title + '</option>');
You should be able to see why if you add a console.log
inside your $.each
to print key
and value
to console. key
will be an int representing the array index, and value
will be the object you're returning from /get/info/
.