Laravel/Javascript: populate a select/dropdown after a different select/dropdown is selected

10,255

Solution 1

The order in which routes are defined in Laravel is crucial. Sometimes you'll be scratching your head and wondering why in the world you're getting an HttpNotFoundException. Consider your routes.php file.

When you define route like Route::controller('/', 'UsersController');, in simple language its greedy route it will not allow routes defined below this route to execute, so when you define this type of route make sure its at the end

So make some change to your route like

Route::get('api/dropdown', function(){
$input = Input::get('option');
$maker = Client::find($input);
$models = $maker->projects();
return Response::eloquent($models->get(array('id','name')));
});
Route::controller('/', 'UsersController');

Solution 2

That tutorial was written for Laravel 3 so somethings will be different. You can tell this because some of the methods are in snake_case rather than camelCase.

return Response::json($models->select(array('id','name'))->get())

That should return a valid json response usable by Javascript. However, you may need to do some edits on your models as well if you followed that tutorial. belongs_to should be belongsTo and has_many should be hasMany.

Share:
10,255
Josh
Author by

Josh

Updated on June 04, 2022

Comments

  • Josh
    Josh almost 2 years

    I'm looking for a solution to populate a dropdown/select (e.g. called dropdown 2) upon selecting an option from another dropdown (e.g. dropdown 1).

    For example, selecting Toyota from dropdown 1 will then populate dropdown 2 with the models of a toyota e.g. Corolla, Camry etc. Or another example - picking a country in one dropdown will populate the different cities of that country in another dropdown.

    I'm using laravel as my framework, so it's important my solution (a) works within laravel and (b) grabs the results from a mysql database, not just a hardcoded array of values.

    I have tried to implement a solution from this post here: http://forums.laravel.io/viewtopic.php?pid=40028

    But it's not working within my setup. This is what I have:

    My view looks like this:

    {{ Form::open() }}
        <select id="make" name="make">
            <option>Select Car Make</option>
            <option value="1">Toyota</option>
            <option value="2">Honda</option>
            <option value="3">Mercedes</option>
        </select>
        <br>
        <select id="model" name="model">
            <option>Please choose car make first</option>
        </select>
    {{ Form::close();}}
    

    Then my route.php looks like this:

    Route::get('api/dropdown', function(){
        $input = Input::get('option');
        $maker = Client::find($input);
        $models = $maker->projects();
        return Response::eloquent($models->get(array('id','name')));
    });
    

    And finally, my script looks like this:

    jQuery(document).ready(function($){
    $('#make').change(function(){
            $.get("{{ url('api/dropdown')}}", 
                { option: $(this).val() }, 
                function(data) {
                    var model = $('#model');
                    model.empty();
    
                    $.each(data, function(index, element) {
                        model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
                    });
                });
        });
    });
    

    I'm currently getting a javascript error in my console:

    Failed to load resource: the server responded with a status of 500 (Internal Server Error): http://localhost/test-project/api/dropdown?option=1
    Failed to load resource: the server responded with a status of 500 (Internal Server Error): http://localhost/test-project/%7B%7B%20url('api/dropdown')%7D%7D?option=1
    

    I believe I have CSRF tokens on, which apparently may affect things - but I'm really not sure how to work with them so just telling me to fix that wont help, I really need a slight bit of detail on exactly how to fix that (if you think that is the problem).

    Alternatively, perhaps a modified or better solution would work better? I'm sure there are many better ways to implement this type of solution.

    In summary, my question is: how can I fix my code above to work OR what is an alternate or better way to populate a dropdown list after an option is selected in another dropdown?

    I have poured through what feels like hundreds of solutions but none seem to work for me and my laravel-ness!

    Edit:

    Complete route looks like this:

    Route::resource('clients', 'ClientsController');
    
    Route::resource('tasks', 'TasksController');
    
    Route::controller('rates', 'RatesController');
    
    Route::controller('projects', 'ProjectsController');
    
    Route::controller('users', 'UserManagementController');
    
    Route::controller('/', 'UsersController');
    
    Route::get('api/dropdown', function(){
        $input = Input::get('option');
        $maker = Client::find($input);
        $models = $maker->projects();
        return Response::eloquent($models->get(array('id','name')));
    });