Laravel refresh data after ajax

25,409

Solution 1

You can put the part in your template corresponding to the table in a separate .blade.php file, and @include that in your main layout.

main.blade.php :

<html>
...
<body>
  <div class="table-container">
  @include('table')
  </div>
</body>
...

And

table.blade.php:

<table>
  @foreach($rows as $row)
    <tr>
      <td> $row->title ... </td>
    </tr>
  @endforeach
</table>

In this way you can use a simple jQuery $('div.table-container').load(url) and on your server just render and respond that part as an html string. return view('table', $data)

Javascript:

function refreshTable() {
  $('div.table-container').fadeOut();
  $('div.table-container').load(url, function() {
      $('div.table-container').fadeIn();
  });
}

Solution 2

The answer is yes, you can. Webinan certainly pointed you in the right direction. This approach is slightly different.

First things first, you need a seperate view for the table. A very basic example for the HTML markup:

<div class="table-container">
    @include('partials.table') // this view will be async loaded
</div>

We start by making a call to the server with jQuery (can be done with Javascript too) using the shorthand ajax function: var $request = $.get('www.app.com/endpoint');. You can also pass along any data to your controller on the backend.

Now on the serverside, within your controller, render and return the table view:

class EndpointController extends Controller
{
    /**
     * Returns a rendered table view in JSON format.
     * 
     * @param  Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajax(Request $request)
    {
        $html = view('partials.table', compact('view'))->render();

        return response()->json(compact('html'));
    }
}

If everything worked out, the done callback will be triggered. Simply grab the html variable and set it as the content of the table's container.

function renderTable() {
    var $request = $.get('www.app.com/endpoint'); // make request
    var $container = $('.table-container');

    $container.addClass('loading'); // add loading class (optional)

    $request.done(function(data) { // success
        $container.html(data.html);
    });
    $request.always(function() {
        $container.removeClass('loading');
    });
}

Hope this helps!

Solution 3

To update and change page content without reloading the page in Laravel 5.4 i do the following:

First create the blade view in the "views" folder called "container.blade.php" it will contain the following code (in this case a select box that is rendering a list of abilities from the package Bouncer (but you can use the @foreach on any Laravel collection you like):

<select>
    {{ $abilityList = Bouncer::role()::where('name','admin')->first()->getAbilities()->pluck('name') }}
    @foreach ( $abilityList as $ab )
        <option value="{{ $ab }}">{{ $ab }}</option>
    @endforeach
</select>

Add this to you main blade file (e.g. home.blade.php) making sure to use a div with an id you can reference:

<div id="abilityListContainer">
    @include('container')
</div>

Now on your main blade file (e.g. home.blade.php) add a button that will trigger the function that will communicate with the Laravel controller:

<input type="button" value="reload abilities" onClick="reloadAbilities()"></input>

Then add the javascript for this function, this loads the generated html into your div container (note the "/updateAbility" route next to ".get" - this is a Laravel route which we will set up in the next step):

    var reloadAbilities = function()
    {
        var $request = $.get('/updateAbility', {value: "optional_variable"}, function(result)
                {
                    //callback function once server has complete request
                    $('#abilityListContainer').html(result.html);
                });
   }

Now we set up the Laravel route for this action, this references our controller and calls the function "updateAbilityContainer". So edit your /routes/web/php file to have the following route:

Route::get('updateAbility', array('as'=> 'updateAbility', 'uses'=>'AbilityController@updateAbilityContainer'));

Finally in app/Http/Controllers make the file "abilityController.php" (you can also use "php artisan make:controller abilityController"). Now add this function to process the changes, generate the html and return it to the javascript function (note you may also have to use the namespaces as well):

   namespace App\Http\Controllers;    

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;

class AbilityController extends Controller
{
    public function updateAbilityContainer()
        {
            // use this if you need to retrieve your variable
            $request = Input::get('value');

            //render and return the 'container' blade view
            $html = view('container', compact('view'))->render();

            return response()->json(compact('html'));
        }
}

Thats it, your blade "container" will now reload when you click the button and any changes to the collection you are rendering should update without reloading the page.

Hopefully this fills in some blanks left in the other answers. I hope it works for you.

Share:
25,409
bradley546994
Author by

bradley546994

Updated on October 06, 2020

Comments

  • bradley546994
    bradley546994 over 3 years

    He is currently working on code that has to filter the data in the table. Ajax will call the link and gets the response (json) results with answer. However, I came across a problem. I have to somehow render tables and I do not want to do this by append etc.

    Can I somehow again generate views or blade file?

    The default view is DefController@index but ajax use url which controller is DefController@gettabledata.

    public function gettabledata($id){
    
        return response()->json(Def::find($id)->getallmy->all());
    
    }