ajax - Serialize Laravel Query Builder -
i able construct query using laravel, , serialize url string. allow me create routes unserialize query builder, run query, , make view displays database results.
for example, implement button refreshes list of posts made kryo:
http://example.com/ajax/posts.php?name=kryo&order_by=created_at&order_type=desc
posts.php route unserializes, validates, , runs query in url params, , provides results view.
perhaps not useful in general, find handy ajax requests. if knows how implement laravel plugin of nature, fantastic.
i'll try give basic idea:
in laravel
have create route
make request function/method, @ first need create route
listening ajax
request, example:
route::get('/ajax/posts', array('uses' => 'postcontroller@index', 'as' => 'showposts'));
now, create link in view points route, create link may try this:
$url = to_route('showposts');
if use this:
<a class='ajaxpost' href="{{ $url }}?name=kryo&order_by=created_at&order_type=desc">get posts</a>
it'll create ink route. so, make sure able pass $url
javascript
or manually can write url
using /ajax/posts?name=...
. once done creating link need create javascript
handler link (maybe using click
event) handle click
event handler, make ajax
request, if it's jquery
this:
$('.ajaxpost').on('clcik', function(e){ e.preventdefault(); var url = $(this).attar('href'); $.getjson(url, function(response){ $.each(response, function(key, value){ // loop... may use $(this) or value }); }); });
in postcontroller
controller class, create 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 view non ajax } } }
if want send rendered view server side javascript
handler html
change getjson
get
, instead of return response::json($posts);
use
return view::make('viewname')->with('posts', $posts);
in case make sure that, view doesn't extends master layout
. may not need gives idea how can implement it.
Comments
Post a Comment