I want to create an AJAX search with Laravel. I'm stuck at the part of displaying the results (posts) returned by the controller. So far I have this:
Search form (home.blade.php)
//The search form
{{ Form::open(array('id' => 'search', 'url' => ' ')) }}
{{ Form::text('query', Input::old('query'), array('placeholder' => 'Search for posts..')) }}
{{ Form::hidden('sort_col', Input::old('sort_col')) }}
{{ Form::hidden('sort_dir', Input::old('sort_dir')) }}
{{ Form::button('<i class="fa fa-search"></i>', array('type' => 'submit', 'name' => 'submit', 'title' => 'Zoeken')) }}
{{ Form::close() }}
Displaying the posts (home.blade.php)
<!-- Posts !-->
<div id="posts">
@if (!$posts->count())
<div class="content">No posts found!</div>
@else
@foreach ($posts as $post)
<div class="list-item clearfix">
<div class="content">
<img src="{{ URL::to($post->thumbnail) }}" alt="" />
<h1>{{{ $post->title }}}</h1>
<div class="tags">
@foreach ($post->tags as $tag)
<abbr title="{{{ $tag->description }}}">{{{ $tag->title }}}</abbr>
@endforeach
</div>
</div>
<div class="score">
{{ $post->rating }}
</div>
</div>
@endforeach
@endif
</div>
<!-- /Posts !-->
HomeController.php
public function postSearch()
{
if (!Request::ajax()) {
return null;
}
$input = array(
'query' => Input::get('query'),
'sort_col' => Input::get('sort_col'),
'sort_dir' => Input::get('sort_dir'),
);
$posts = new Post;
$posts = $posts->select(...)->where(...)->orderBy(...); //Search query here
Input::flash();
return $posts;
}
The postSearch()
method is being called when the search for is submitted.
The jQuery (home.blade.php)
$('#search').submit(function(e) {
e.preventDefault();
var form = $(this);
$.post(form.attr('action'), form.serialize(), function(data) {
$('#posts').html(data);
console.log(data);
});
});
Everything works fine and data is being returned. It looks like this when I log the data into the console:
The objects within the red box are the posts. How do I display those posts in the #posts
div? I've been strugling a while now but I just can't figure it out.