I'm trying to populate a select box based on a previous select box value in Laravel 4. Here's what I have so far:
My JS:
var url = document.location.hostname + '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
alert(url);
label = "<label class='control-label'>Contacts</label>";
select = $("<select name='contact_id[]' id='contact_id'>");
console.log(contacts);
for(var i in contacts) {
alert(contacts[i]['account_id']);
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.contacts').html(select).prepend(label);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController@contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get()->toArray();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController@store', 'class' => 'view-only pull-left form-inline')) }}
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
{{ Form::select('account_id', $accounts) }}
<div class="contacts"></div>
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
{{ Form::select('delegate_status_id', $delegate_statuses) }}
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
{{ Form::text('price', '', array('class' => 'input-small')) }}
{{ Form::hidden('event_id', $event->id) }}
{{ Form::submit('Add Delegate', array('class' => 'btn btn-success')) }}
{{ Form::close() }}
EDIT: I've modified my code above. When I visit /list-contacts it gets the correct data I need, it's just not assigning that data to the contacts variable in my AJAX request in my JS? Any help would be appreciated.
Error: This is the error that is shown in my console log for the contacts variable:
file: "/Applications/MAMP/htdocs/cream/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php" line: 290 message: "" type: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"