Reputation: 101
i had a user list form in laravel. so i want when i click the table row, it automatically load the user details from database without redirecting. i've heard about ajax. but i have no idea how to use it in laravel..
i want to make like this
but without redirecting page..
$("tr").click(function()
{
$.ajax({
type: "GET",
url: $(this).data("href"),
dataType: "text",
success : function(data) {
$('#details-container').load(data)
}
});
});
does it supposed to be like this? but how did i get the data from database? i have no idea. please help me..
Upvotes: 0
Views: 130
Reputation: 3383
<table>
<thead>
...
</thead>
<tbody>
<tr data-details-link="http://your-domain/user/{user-id}/details">
...
</tr>
</tbody>
</table>
$('table tr').on('click', function (event)
{
event.preventDefault();
var $this = $(this);
// not necessary but you should show a loading here
$.ajax({
url: $this.data('details-link')
})
.success(function (response)
{
// the `response` variable is HTML code. Insert it into a modal.
});
});
...
Route::get('user/{id}/details', [ 'uses' => 'UserController@details' ]);
...
UserController
method:public function details($id)
{
$user = \App\User::find($id);
if (!$user)
abort(404);
return view('user.details')->with('user', $user);
}
**Your user/details.blade.php
should have the HTML that will be send as the AJAX response.
Upvotes: 1
Reputation: 14904
Its the same in Laravel as in "native" PHP. With your Ajax request your are able to send and asynchronous request, and refresh just a little part of your website, so you dont need to reload your whole page.
If you want to make it work with laravel, you should:
create a route for your requests
Route::get('user/{id}', function($id)
{
// So all your GET requests with any user id goes to this script (in routes.php)
// here you should load your user information, maybe with ORM
$user = User::where('id','=',$id)->get();
// Build any HTML snippet, or build JSON data (and build the information in Javascript on your page)
//return here JSON / or html
$data = array() -> containts information for the blade template
return view('users.information', $data);
});
Your AJAX request returns now JSON / or HTML, append it to your site where you would like to show it.
Upvotes: 1