Nanda Pandyatama
Nanda Pandyatama

Reputation: 101

laravel 5 ajax request

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 enter image description here

enter image description here

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

Answers (2)

Hkan
Hkan

Reputation: 3383

Your page structure will be like this:

<table>
  <thead>
    ...
  </thead>

  <tbody>
    <tr data-details-link="http://your-domain/user/{user-id}/details">
      ...
    </tr>
  </tbody>
</table>

The page with the table, should have this jQuery codes:

$('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.
    });
});

Your route:

...
Route::get('user/{id}/details', [ 'uses' => 'UserController@details' ]);
...

Your 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

derdida
derdida

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:

  1. 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);
    
    });
    
  2. Your AJAX request returns now JSON / or HTML, append it to your site where you would like to show it.

Upvotes: 1

Related Questions