jeudi 3 mars 2016

Laravel 5: Cascading dropdown doesn't work

I want to make a cascading dropdownlist when If i select a category subcategories also will be changed . I used Ajax here.I don't know why my subcategories couldn't load in the view while i select category list from dropdown.

Here is my routes:

<?php

Route::get('/', function () {

     $categories=\App\Category::all();
    return view('index')->with ('categories',$categories);

});

Route::get('/ajax-subcat',function(){
    $cat_id = Input::get('cat_id');
    $subcategories=Subcategory::where('category_id','=',$cat_id)->get();
    return Response::json($subcategories);
});

And here is my View page:

<html>
    <head>
        <title>Cascading Dropwon</title>
        <link rel="stylesheet" href="http://ift.tt/1JetChn">
  <script src="http://ift.tt/1ROJ5xx"></script>
    </head>
    <body>
        <div class="container">
            <h3>Categories and Subcategories Ajax</h3>
            <div class="col-lg-4">
                {!! Form::open(array('url' => '','files'=>true))  !!}
                {!! Form::token(); !!}
                    <div class="form-group">
                        <label for="">Categories</label>
                        <select class="form-control input-sm" name="category" id="category">
                        @foreach($categories as $category){
                        <option value="{{$category->id}}">{{$category->name}}</option>
                        }
                        @endforeach
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="">Sub Categories</label>
                        <select class="form-control input-sm" name="subcategory" id="subcategory">
                        <option value=""></option>
                        </select>
                    </div>


                {!!Form::close()!!}
            </div>
        </div>
        <script>
            $('#category').on('change',function(e){
                console.log(e);
                var cat_id = e.target.value;

                $.get('/ajax-subcat?cat_id='+ cat_id,function(data){
                    $('#subcategory').empty();
                    $.each(data,function(index,subcatObj){
                        $('#subcategory').append('<option value="'+subcatObj.id+'">'+
                                                    subcatObj.name+'</option>');
                    });

                });
            });
        </script>
    </body>

</html>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Y4IJCF
via IFTTT

Aucun commentaire:

Enregistrer un commentaire