3

I'm using a dynamic dropdown list in my form I want to choose an area according to the chosen city
this is my view

 <div class="form-group col-md-6 form-group{{ $errors->has('city') ? ' has-error' : '' }}">
    <label for="inputPassword4" style="padding-left:35em"><span style="color:red">*</span> city</label>
    <select id="city" name="city" class="form-control">
        <option ></option>
        @foreach($cities as $city)
         <option value="{{$city->id}}">{{$city->city}}</option>
        @endforeach
    </select>
    <h6 class="text-danger">{{ $errors->first('city') }}</h6>
    </div>
</div>

    <div class="form-group col-md-6 form-group{{ $errors->has('area') ? ' has-error' : '' }}">
    <label for="inputEmail4" style="padding-left:50em">area</label>
    <select id="area" name="area" class="form-control">
        <option></option>
    </select>
    <h6 class="text-danger">{{ $errors->first('area') }}</h6>
    </div>

and this is the script

    $('#city').on('change',function(e){

            console.log(e);

        var city= e.target.value;

        $.get('/areas/'+ city, function (data){

              //console.log(data);
            $('#area').empty();

            $.each(data,function(i,area){

            $('#area').append('<option value ="'+area+'">'+area+'</option>');

            });
        });
    });
</script>e

the controller

 public function areas($id)
{

    $area = area::where('city_id', $id)->pluck("area","id");

    return Response::json($area);
}

routs :

Route::get('/areas/{id}', 'locationController@areas');

i used this code but it didn't work!

1
  • var city= e.target.value; alert this means debug this whats the value you are getting? Commented Dec 21, 2019 at 13:45

1 Answer 1

2

Instead of return Response::json($area); use return response()->json($cities);

Your controller will be:

public function areas($id)
{

    $area = area::where('city_id', $id)->pluck("area","id");

    return response()->json($area);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Can you show your route from web.php. And what are you getting as a response? Can you check from your Inspect -> Network (for chrome)
i added the route to the question code . what should i see as a response in the network?
when I call the rout areas/id in the URL it returns the areas perfectly.
if you uncomment console.log(data); on your script. What are you getting?
web.php: Route::get('/areas/{id?}', 'locationController@areas')->name('areas'); Script: $.get('{{route('areas')}}/'+ city, function (data){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.