Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maaz's avatar
Level 2

Dynamic Dependent Drop down box not working using ajax in laravel .

i was looking for a dynamic dependent dropdown selectbox, so i found a video i copy the code line by line from him but my code is not working idk why. here is my MainController.php

<?php

namespace App\Http\Controllers;

use App\State;
use App\Country;
use Illuminate\Http\Request;

class MainController extends Controller
{
    public function index()
    {
        $countries = Country::all();
        return view('index', compact('countries'));
    }

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

My routes:

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

index.blade.php:

  <div class="panel panel-primary">
        <div class="panel-heading">
            <h2 class="text-center">Multi Dropdown</h2>
        </div>
        <div class="panel-body">
            <div class="col-md-3">
                <select name="country" id="country" class="form-control">
                    <option value="" selected="false">Country</option>
                    @foreach ($countries as $country)
                    <option value="{{$country->id}}">{{$country->name}}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-6 mt-3">
                <select name="state" id="state" class="form-control">
                    <option value="" selected="false">State</option>
                </select>
            </div>
        </div>

        <div class="col-md-3 mt-3">
            <button class="btn btn-primary rounded" type="submit" name="search">Search <i
                    class="fa fa-search"></i></button>
        </div>
    </div>

Jquery code:

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

it is not working :(

0 likes
19 replies
MichalOravec's avatar

You don't need json_encode so

<?php

namespace App\Http\Controllers;

use App\State;
use App\Country;
use Illuminate\Http\Request;

class MainController extends Controller
{
    public function index()
    {
        $countries = Country::all();
        return view('index', compact('countries'));
    }

    public function getStates($id)
    {
        return State::where('country_id', $id)->pluck('name', 'id');
    }
}
MichalOravec's avatar

What do you get when you true console.log(data); inside ajax success method?

maaz's avatar
Level 2
(index):47 Uncaught ReferenceError: JQuery is not defined
    at HTMLSelectElement.<anonymous> ((index):47)
    at HTMLSelectElement.dispatch (app.js:11800)
    at HTMLSelectElement.elemData.handle (app.js:11604)

but jquery is loaded already

MichalOravec's avatar

Instead of jQuery or JQuery just use $

Like

$.ajax({
    // 
});

Also jquery has to be loaded before your code in <script> tag.

maaz's avatar
Level 2

@michaloravec now there is no error in the console. but I didn't get my required results.

maaz's avatar
Level 2

@michaloravec yes I have data in my countries and states table. I also make their relationship so there should be no problem.

maaz's avatar
Level 2

@michaloravec thanks for you precious time buddy, it will be great if you solve my this problem :)

MichalOravec's avatar

If you run this in browser you should get some data, for country with id 1.

http://example.com/getStates/1

Of course replace example.com woth what you use.

If you don't get data check your db connection, etc.

maaz's avatar
Level 2

@michaloravec

 public function getStates($id)
    {

        $states = State::where('country_id', $id)->pluck('name', 'id');
        dd($states);
    }

i am getting data when i visit the /getStates/1

maaz's avatar
Level 2

@michaloravec i just done it by adding this to my code.

  public function getStates($id)
    {

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

return resonse()->json($state) it works

MichalOravec's avatar
Level 75
<script>
    $(function() {
        $('select[name="country"]').on('change', function () {
            var countryID = $(this).val();

            if (countryID) {
                $.get('/getStates/' + countryID, function(data) {
                    $('select[name="state"]').empty();

                    $.each(data,function(key, value) {
                        $('select[name="state"]').append('<option value="' + key + '">' + value + '</option>');
                    });
                }, 'json');
            } else {
                $('select[name="state"]').empty();
            }
        });
    });
</script>
1 like
MichalOravec's avatar

Just this should return json, but great if it works.

return State::where('country_id', $id)->pluck('name', 'id');

Please or to participate in this conversation.