I´m trying to make a filter using Ajax, I want to display images based on the chosen category in the dropdown, whenever it changes. Right now I´m displaying all images in my view and I want to make an Ajax call that returns the filtered $images array to display in the view. But I´m stuck. I can't figure out how to return the data from the controller correct, so I can access it in the view.
Form with dropdown in the index.blade.php
{{ Form::open( array(
'route' => 'index.filter',
'method' => 'post',
'id' => 'form-filter'
) ) }}
{{ Form::select('category', $categories, 'default', array('id' => 'categories')) }}
{{ Form::close() }}
routes
Route::post( 'filter', array(
'as' => 'index.filter',
'uses' => 'MyController@filter'
) );
.js
$( '#form-filter' ).change( function() {
$.post(
$( this ).prop( 'action' ),
{
"id": $( '#categories' ).val()
},
function( data ) {
alert(data);
},
'json'
);
return false;
} );
controllers
public function filter()
{
Log::info(Input::get('id'));
$id = Input::get( 'id' );
if($id)
$images = Image::where('category_id', '=', $id);
return Response::json($images);
}
public function index()
{
$images = Image::all();
$categories = ..\Models\Category::lists('name', 'id');
return View::make('index', array('images' => $images, 'categories'=>$categories));
}