karmendra karmendra - 4 months ago 39
Ajax Question

Laravel 5.1 Ajax to get html from Blade View

I have a myitems($filter) method in a ItemsController that loads the myitems.blade view.

The view has list of items as label and text box to get number of items ($items is passed from myitems method to myitems view and there is a model form binding on items model as well)

I have a select box that has options 1. All, 2. Expired and 3.New

When I change the selection I want to have get new $items from the controller and recreate the form with new items list.

I am using using jquery to alert that the selection is changed. but I am not able to figure out how will I be able to call myitems($filter) from ajax and redirect to create the items.blade page.

Answer

Route

//Note the ? in parameter, it says parameter is optional
Route::get('/myitems/{filter?}', 
    ['as' => 'myitems.list', 'uses' => 'ItemController@myitems']
);

Controller

...
public function myitems(Request $request, $filter = null)
{
    if (empty($filter)) $filter=1;

    $items = Item::where('item_type', $filter)->get();

    // if ajax call just return the partial that displays the list
    if ($request->ajax()) {
        return view('_itemlist', compact('items'));
    }

    // passed as options to input select
    $filters= [
           'All' => '0',
           'New' => '1',
           'Expired' => '2'
    ];
    return view('itempagewith_defaultitemlist', compact('items','filters'));
}
...

View

view itempagewith_defaultitemlist.blade.php

<div class="container">
{!! Form::model($myitems, ['route' => 'myitems.list', 'class'=>'form-horizontal', 'files' => true]) !!}

<div id="filterselectbox">
    <div class="form-group">
            {!!Form::label('filterselectbox','*Filter:',['class'=>'control-label']) !!}            
            {!!Form::select('filterselectbox', $filters, null, ['class'=>'form-control ']) !!}
     </div>
</div>
@include('_itemlist')

{!! Form::close() !!}
</div>

partial view _itemlist.blade.php

<div id="item-container">
     <ul>
     @foreach ($items as $item)
        <li>{{ $item->name }}</li>
     @endforeach
     </ul>
</div>

<script>
$('#filterselectbox').change(function() {
    var id = $('#filterselectbox').val();
    var ajaxurl = '{{route('myitems', ':id')}}';
    ajaxurl = ajaxurl.replace(':id', id);
    $.ajax({
        url: ajaxurl,
        type: "GET",
        success: function(data){
            $data = $(data); // the HTML content that controller has produced
            $('#item-container').hide().html($data).fadeIn();
        }
    });
});
</script>
Comments