0

I have dropdown menu in template Laravel.

This is select list with names of countries.

I need to load cities in the closest dropdown menu after clicking by item of country.

So, I think it should be Ajax request to controller Laravel, that to get cities by id country.

Maybe there is any solution?

0

1 Answer 1

2

You could do something like this in jQuery

<select class="country">
     <option>Select</option>
     <option value="usa">United States</option>
     <option value="india">India</option>
     <option value="uk">United Kingdom</option>
</select>
<input type="hidden" name="_token" value="{{ csrf_token() }}">

<div id="response"></div>

The javascript, don't forget to put it inside $(document).ready()

$("select.country").change(function(){
   var selectedCountry = $(".country option:selected").val();

   $.ajaxSetup({
        headers: {
             'X-CSRF-TOKEN': '{{csrf_token()}}'
        }
   });

   $.ajax({
        method: "POST",
        url: "countriesList",
        data: { country : selectedCountry }
        }).done(function(data){
             $("#response").html(data);
        });
 });

And then in your Laravel Controller or directly from the route, you could return the countries and cities as multi-dimensional arrays

Route::post('countriesList', function() {
    if(Request::ajax()) {
        $country = Input::get('country');

        $countryArr = [
            "usa" => ["New York", "Los Angeles", "California"],
            "india" => ["Mumbai", "New Delhi", "Bangalore"],
            "uk" => ["London", "Manchester", "Liverpool"]
        ];

        if($country !== 'Select'){
            echo "<label>City:</label>";
            echo "<select>";
            foreach($countryArr[$country] as $value){
                echo "<option>". $value . "</option>";
            }
            echo "</select>";
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.