karmendra karmendra - 1 year ago 171
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 Source


//Note the ? in parameter, it says parameter is optional
    ['as' => 'myitems.list', 'uses' => 'ItemController@myitems']


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 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 ']) !!}

{!! Form::close() !!}

partial view _itemlist.blade.php

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

$('#filterselectbox').change(function() {
    var id = $('#filterselectbox').val();
    var ajaxurl = '{{route('myitems', ':id')}}';
    ajaxurl = ajaxurl.replace(':id', id);
        url: ajaxurl,
        type: "GET",
        success: function(data){
            $data = $(data); // the HTML content that controller has produced
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download