maaz's avatar
Level 2

Dynamic Dependent dropdown error

Hey everyone, i have a list of countries and states, when someone click on a country it will show the related states of that country. here is my code

route

Route::get('/getStates/{id}', 'StateController@getStates')->name('getStates');

StateController.php

 public function getStates($id)
    {
        $states = State::where('country_id', $id)->pluck('name', 'id');
        return response()->json($states);
    }

blade.php

 <div class="form-group">
                            <label for="country">Country</label>
                            <select name="country" class="form-control" id="country">
                                <option value="" selected disabled>Select Country</option>
                                @foreach ($countries as $country)
                                <option value="{{$country->id}}">{{$country->name}}</option>
                                @endforeach


                            </select>
                        </div>

                        <div class="form-group">
                            <label for="state">State</label>
                            <select id="state" name="state" class="form-control">
                                <option value="" selected="false">State</option>
                            </select>
                        </div>

ajax

<script>
    // Dynamic dependent dropdowns for province
        $(document).ready(function (){
        $('select[name="country"]').on('change',function(){
        var countryID = $(this).val();
        if (countryID) {
        $.ajax({
        url:'/getStates/'+countryID,
        type: 'GET',
        dataType:'json',
        success:function(data){
        $('select[name="state"]').empty();
        $.each(data,function(key,value){
        $('select[name="state"]').append('<option value="'+ key +'">'+value+'</option>');
        });
        }
        });
        }
        else{
        $('select[name="state"]').empty();
        }
        });
        });
</script>

error in console

Failed to load resource: the server responded with a status of 404 (Not Found)
0 likes
0 replies

Please or to participate in this conversation.