Tuesday 20 March 2018

Ajax Dynamic Dependent Dropdown in Laravel


This tutorial cover how to make dynamic dependent select box by using Ajax JQuery in Laravel framework. This is new post on Laravel with Ajax tutorial and in this we have developed simple Country State and City Dynamic Dependent dropdown list box in Laravel by using JQuery Ajax. Dynamic Dependent means child drop down list data has been filled when we have select parent drop down list box. e.g. In Country State City dynamic dependent select box example, when we have select particular country in select box then in state select box has been filled with state data of selected country and when we have select particular state in select box then city select box has been filled with list of city of selected state. This way this dynamic dependent dropdown list box has been working.

Here we have use Ajax with Laravel for developed dynamic dependent select box. When we have select parent select box then it will send Ajax request to Laravel code for fetch data for child select box. So this way child select box has been filled with data. This whole process has been done without refresh of web page because we have use Ajax with Laravel. We have already publish this dynamic dependent select box tutorial by using PHP with Ajax but now we have publish in Laravel framework also. Because there are many programmers has been use Laravel framework for their web development.




For this first we have to make one controller for handle HTTP request for this feature. For this we have to write following command in command prompt.


php artisan make:controller DynamicDependent


This command will make DynamicDependent.php controller under app/HTTP/controllers folder. In this controller first we have to make index() method. This method will load view file with three dynamic select box like country, state and city. In which country select box has been filled with country data and state and city select box will be blank. Both drop down list box data has been filled when we have select country select box.


<?php

//DynamicDepdendent.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class DynamicDependent extends Controller
{
    function index()
    {
     $country_list = DB::table('country_state_city')
         ->groupBy('country')
         ->get();
     return view('dynamic_dependent')->with('country_list', $country_list);
    }

?>


This code will load dynamic_dependent.blade.php view file with three drop down list of Country, state and city. This code will filled country dropdown list box with data and other two select box will be blank. Below you can find source code of view file.


<!DOCTYPE html>
<html>
 <head>
  <title>Ajax Dynamic Dependent Dropdown in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Ajax Dynamic Dependent Dropdown in Laravel</h3><br />
   <div class="form-group">
    <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
     <option value="">Select Country</option>
     @foreach($country_list as $country)
     <option value="{{ $country->country}}">{{ $country->country }}</option>
     @endforeach
    </select>
   </div>
   <br />
   <div class="form-group">
    <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
     <option value="">Select State</option>
    </select>
   </div>
   <br />
   <div class="form-group">
    <select name="city" id="city" class="form-control input-lg">
     <option value="">Select City</option>
    </select>
   </div>
   {{ csrf_field() }}
   <br />
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 $('.dynamic').change(function(){
  if($(this).val() != '')
  {
   var select = $(this).attr("id");
   var value = $(this).val();
   var dependent = $(this).data('dependent');
   var _token = $('input[name="_token"]').val();
   $.ajax({
    url:"{{ route('dynamicdependent.fetch') }}",
    method:"POST",
    data:{select:select, value:value, _token:_token, dependent:dependent},
    success:function(result)
    {
     $('#'+dependent).html(result);
    }

   })
  }
 });

 $('#country').change(function(){
  $('#state').val('');
  $('#city').val('');
 });

 $('#state').change(function(){
  $('#city').val('');
 });
 

});
</script>


In this code we have also write jquery code on select box change event. In country and state select box we have define .dynamic. We have use this class as selector in jquery code. When we have select any option then jquery code will be run and in that we have use Ajax request to fetch() method for send data to server. On server side it will fetch particular state or city data and send back to Ajax request. Based on value of data-dependent attribute in which we have store id of child select box. And based on that value particular state or city drop down list box has been filled.


<?php

//DynamicDepdendent.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class DynamicDependent extends Controller
{
    function index()
    {
     $country_list = DB::table('country_state_city')
         ->groupBy('country')
         ->get();
     return view('dynamic_dependent')->with('country_list', $country_list);
    }

    function fetch(Request $request)
    {
     $select = $request->get('select');
     $value = $request->get('value');
     $dependent = $request->get('dependent');
     $data = DB::table('country_state_city')
       ->where($select, $value)
       ->groupBy($dependent)
       ->get();
     $output = '<option value="">Select '.ucfirst($dependent).'</option>';
     foreach($data as $row)
     {
      $output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
     }
     echo $output;
    }
}

?>


Lastly, We have to set route for index() and fetch() method of DynamicDepdendent.php Controller class. For this we have to go to routes/web.php file.


<?php


Route::get('/', function () {
    return view('welcome');
});


Route::get('/dynamic_dependent', 'DynamicDependent@index');

Route::post('dynamic_dependent/fetch', 'DynamicDependent@fetch')->name('dynamicdependent.fetch');

?>


This is complete source of Dependent Country State City Dropdown using Ajax JQuery in Laravel. For download complete source code with file, please download from by clicking on below link.




25 comments:

  1. If save as database,
    How to do the edit page? Thanks.

    ReplyDelete
  2. didnot worked for me..i have province_number, district and local_bodies_name.. and last two are blank

    ReplyDelete
  3. $.ajax is not a function why??


    $(document).ready(function(){

    $('.dynamic').change(function(){
    if($(this).val() != '')
    {
    var select = $(this).attr("id");
    var value = $(this).val();
    var dependent = $(this).data('dependent');
    var _token = $('input[name="_token"]').val();
    $.ajax({
    url:"{{ route('dynamic_dependent.fetch') }}",
    method:"POST",
    data:{select:select, value:value, _token:_token, dependent:dependent},
    success:function(result)
    {
    $('#'+dependent).html(result);
    }

    });
    }
    });

    $('#province_number').change(function(){
    $('#district').val('');
    $('#local_bodies_name').val('');
    });

    $('#district').change(function(){
    $('#local_bodies_name').val('');
    });


    });


    ReplyDelete
  4. can't download this source code ...Can you help me pls

    ReplyDelete
  5. source code cant download or give me database sql

    ReplyDelete
  6. hello sir thanks for your great tutorials, please can i have the database??

    ReplyDelete
  7. Thanks for the tutorial. It works fine for entering data. But when editing, all data from the drop downs do not show. Is there a way to keep the data when editing? Thanks

    ReplyDelete
  8. Thank You ! This helped me.

    But i was facing error while using .selectpicker so i refreshed .selectpicker and it worked.

    $('.selectpicker').selectpicker('refresh');

    ReplyDelete
  9. i have a employee creation form with country,state,city dropdown and other fields also like name,email,etc.I created 3 different tables for country,state and city and used ajax and jquery for dropdown. Dropdown is working fine but when i submit form countryid,stateid and cityid stored in database instead of countryname,statename and cityname. Please suggest how to get name fields in table.

    ReplyDelete
  10. hello sir add two more dropdown box could not work

    ReplyDelete
  11. Hello this is the creating section what if I need to edit the same 2 menus how to retrieve data

    ReplyDelete
  12. i want the complete of this tutorial

    ReplyDelete
  13. how can make database and column

    ReplyDelete
  14. why i got POST 500 (Internal Server Error)

    ReplyDelete
    Replies
    1. Hola Ohoc, yo tengo el mismo error lograste solucionarlo?

      Delete
  15. Thankyou. Can you explain why my form for "select option" value is null on post to server?

    ReplyDelete
  16. SQLSTATE[42000]: Syntax error or access violation: 1055 'dashboard.country_state_city.state' isn't in GROUP BY (SQL: select * from `country_state_city` group by `country`)
    showing this error

    ReplyDelete
  17. not working i am try a lots of time but its not work

    ReplyDelete