I'll try to give you a basic idea:
In Laravel
you have to create a route
to make a request to a function/method, so at first you need to create a route
which will be listening for the ajax
request, for example:
Route::get('/ajax/posts', array('uses' => 'PostController@index', 'as' => 'showPosts'));
Now, create a link in the view which points to this route, to create a link you may try this:
$url = to_route('showPosts');
If you use something like this:
<a class='ajaxPost' href="{{ $url }}?name=kryo&order_by=created_at&order_type=desc">Get Posts</a>
It'll create a ink to that route. So, make sure you are able to pass that $url
to your JavaScript
or manually you can write the url
using /ajax/posts?name=...
. Once you done creating the link then you need to create your JavaScript
handler for this link (maybe using click
event) then handle the click
event from your handler, make ajax
request, if it's jQuery
then it could be something like this:
$('.ajaxPost').on('clcik', function(e){
e.preventDefault();
var url = $(this).attar('href');
$.getJSON(url, function(response){
$.each(response, function(key, value){
// loop... you may use $(this) or value
});
});
});
In your PostController
controller class, create the index method:
class PostController extends BaseController {
public function index()
{
$name = Input::get('name');
$order_by = Input::get('order_by');
$created_at = Input::get('created_at');
$order_type = Input::get('order_type');
$posts = Post::whereName($name)->orderBy($order_by, $order_type)->get();
if(Request::ajax()) {
return Response::json($posts);
}
else {
// return a view for non ajax
}
}
}
If you want to send a rendered view from the server side to your JavaScript
handler as HTML
then change the getJson
to get
and instead of return Response::json($posts);
use
return View::make('viewname')->with('posts', $posts);
In this case make sure that, your view doesn't extends the master layout
. This may not be what you need but it gives you the idea how you can implement it.