Laravel 9 Ajax Multiple Conditional Dropdown

PHOTO EMBED

Sat Oct 08 2022 10:20:04 GMT+0000 (Coordinated Universal Time)

Saved by @ahmad007 #laravel #ajax

---------write it in head section in blade template-----------------
<meta name="csrf-token" content="{{csrf_token()}}"> 
  ----------do not use slim version of J Query---------------
    --------Use this before document ready in script tag--------
    <script>
          $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
    </script>
------------------then------------------------------------
 <script>
        $(document).ready(function(){
            $('#country').change(function(){
                var country_id = $(this).val();
                $('#city').html('<option value="">Select City</option>');
                
                $.ajax({
                    url: '/getState/'+country_id,
                    type:'post',
                    success: function(result){
                        $('#state').html(result);
                    }
                });
            });

            $('#state').change(function(){
                var state_id = $(this).val();

              
                
                $.ajax({
                    url: '/getCity/'+state_id,
                    type:'post',
                    success: function(result){
                        $('#city').html(result);
                    }
                });
            });
        });
    </script>
--------------------------web.php code--------------------------
Route::post('/getState/{id}', [PlaceController::class, 'getState']);
Route::post('/getCity/{id}', [PlaceController::class, 'getCity']);
-------------------------Controller Code -----------------------------
  public function getState($country_id){
        $states = State::where('country_id', $country_id)->get();
        $html = '';
        foreach($states as $state){
            $html .='<option value="'.$state->id.'">'.$state->state_name.'</option>';
        }
        echo $html;
    }

    public function getCity($state_id){
        $cities = City::where('state_id', $state_id)->get();
        $html = '';
        foreach($cities as $city){
            $html .='<option value="'.$city->id.'">'.$city->city_name.'</option>';
        }
        echo $html;
    }
content_copyCOPY