How to use AJAX in DropDown in Laravel? Example as in Country, State, and City.
To Click Part-1 of its first blog. Now, we’ll start the next part of this.
Inserting data into Country, State and City tables
Step 15. We can insert data into tables through CRUD functions or directly by Database. Here, we go direct to insert data into tables. Go to http://localhost/phpmyadmin -> Click your created database country_state_city ->Click countries table ->Click Insert.
Step 16. As well, we have to insert data into states and cities tables.
Step 17. Go to resources/views/welcome.blade.php file and give a link. Laravel provides a helper function, asset(), which generates a URL to application assets(CSS/JavaScript/images files).
{{asset('css/app.css')}}
Step 18. As well, we have to generate url js file by asset() function. Go to Download the compressed, production jQuery 3.5.1 right-click the link, copy all and paste within public/js folder->create jquery.js file.
<script src="{{asset('js/jquery.js')}}"></script>
Step 19. Write logic of DropDown selection using AJAX for Country within welcome.blade.php file
<script>
$(document).ready(function(){
$('select[name="country"]').on('change',function(){
var country_id= $(this).val();
if (country_id) {
$.ajax({
url: "{{url('/getStates/')}}/"+country_id,
type: "GET",
dataType: "json",
success: function(data){
console.log(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>
Step 20. Similarly, write logic of DropDown selection using AJAX for State.
Here’s the full code.
Whenever we select the name of country so automatically the name of the states’ list will have appeared. As well as, Cities’ list will be appeared on clicking the name of the state.
Thanks
- How to Login with Token in Laravel PHP Framework? - October 30, 2021
- How to merge two or multiple tables to each other in the Laravel PHP Framework? (Part-4) - October 29, 2021
- How to display a table in a Verticle or Horizontal form in the Laravel PHP Framework? Part-2 - October 29, 2021