0

My html is like this :

<div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}">
    <select class="form-control" name="kdkotama" id="kdkotama">
        <option value="">---- Pilih Kotama----</option>
        @foreach($tkotam as $tkotam)
        <option value="{{$tkotam->kdkotama}}">{{$tkotam->nmkotama}}</option>
        @endforeach
    </select>

    @if ($errors->has('kdkotama'))
        <span class="help-block">
            <strong>{{ $errors->first('kdkotama') }}</strong>
        </span>
    @endif
</div>

<div class="form-group has-feedback{{ $errors->has('kdsatker') ? ' has-error' : '' }}">
    <select class="form-control" name="kdsatker">
        <option value="">---- Pilih Satker ----</option>
    </select>

    @if ($errors->has('kdsatker'))
        <span class="help-block">
            <strong>{{ $errors->first('kdsatker') }}</strong>
        </span>
    @endif
</div>

My javascript is like this :

<script>
    $(document).ready(function() {
        $("#kdkotama").change(function() {
            console.log($("#kdkotama").val());
            $.getJSON("../dropdowns/satkers/" + $("#kdkotama").val(), function(data) {
                var $satkers = $("#kdkotama");
                $satkers.empty();
                $.each(data, function(index, value) {
                    $satkers.append('<option value="' + index +'">' + value + '</option>');
                });
                $("#kdkotama").trigger("change"); /* trigger next drop down list not in the example */
            });
        });
    });
</script>

My routes/web is like this :

Route::get('dropdowns/satkers/{id}', 'DropDownController@getSatkers');

My controller is like this :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TSatkr

class DropDownController extends Controller
{
    public function getSatker($id)
    {
        $satkers = TSatkr::where('kdkotama', '=', $id)->get();
        $options = array();

        foreach ($satkers as $satker) {
            $options += array($satker->kdsatkr => $satker->nmsatkr);
        }

        return Response::json($options);
    }
}

I added this: console.log ($ ("# kdkotama"). val ()); in javascript. when I select kotama, the results of console.log that appear. but in the console, it did not succeed in calling controller. whereas the code, it looks like it is correct

is there anyone who can help me?

samuel toh
  • 6,836
  • 21
  • 71
  • 108
  • u may see this http://stackoverflow.com/questions/41081705/how-to-fix-dynamic-dropdown-list-with-ajax-error/41083021#41083021 – Borna Dec 11 '16 at 15:30

1 Answers1

0

I faced so many problem to generate dynamic drop-down but now I do like this which is more powerful and useful to set dynamic drop-down value.

Lets generate DOM using method which can help us to generate dynamic DOM with one truth or source..

//Controller/HelperController.php
class HelperController
{
  public static function ajaxDynamicDropDown($changeDropdown, $replaceDropdown, $url, $empty = []) {
    $html = '<script type="text/javascript">';
    $html.='jQuery(document).ready(function($) {';
    $html.='jQuery("select[name=\'' . $change_dropdown . '\']").change(function(e){';
    $html.='jQuery.ajax({';
    $html.='type: "'.$action_type.'",';
    $html.='url: "' . $url . '",';
    $html.='dataType:"json",';
    $html.='data: jQuery(this).parents("form").find("input,select").not("[type=hidden][name^=_]").serialize(),';
    $html.='success:function(data){';
    $html.='    jQuery("select[name=\'' . $replace_dropdown . '\']").find("option:not(:first)").remove();';
    if (!empty($empty)) {
        foreach ($empty as $key => $emt) {
            $html.='    jQuery("select[name=\'' . $emt . '\']").find("option:not(:first)").remove();';
        }
    }
    $html.='    jQuery.each(data, function(key,value){';
    $html.='        jQuery("select[name=\'' . $replace_dropdown . '\']").append(\'<option value="\'+key+\'">\'+value+\'</option>\');';
    $html.='});';
    $html.='}';
    $html.='});';
    $html.='});';
    $html.='});';
    $html.='</script>';
    return $html;
}    

}

Benefit of it is I don't have to write change event for each dropdown. Also no need trigger.

// Blade File:

{!! Form::select('country_id',['1'=>'Test 1','2'=>'Test 2'],null,[]) !!} // First Dropdown with value
{!! Form::select('state_id',[],null,[]) !!}  // Second Dropdown will set based on first one.

<script type="text/javascript">
{!! HelperController::ajaxDynamicDropDown('country_id','state_id',URL::to('ajax/states'),['state_id','city_id']) !!}
</script>

Now I am going to use implicit route controller. Using that I get controller methods based on the HTTP request type and name.

Mean in ajax if I used POST method request then in my controller my method name will be like postState() or if GET request then same getState(). For more please click here

//routes.php
Route::controller('ajax', 'AjaxController');

Here is code sample of AjaxController

// AjaxController.php
class AjaxController
{
    public function postState()
    {
    // of course here I get Input by using request()->get('input_name')
        return ['1'=>'test'];
    }
}

Also you can set old value when validation going false with old() in AjaxController.

You can also use it for multiple dependencies like state if came from country now it can be possible you need to get city from state same method you can use for it..

Community
  • 1
  • 1
Gautam Patadiya
  • 1,401
  • 14
  • 19