yoeunes / toastr

:eyes: toastr.js notifications for Laravel
https://php-flasher.io
MIT License
375 stars 52 forks source link

Using toastr with ajax #20

Closed samuelhgf closed 4 years ago

samuelhgf commented 4 years ago

Description:

Hi, there is any way to render the toastr without refresh or redirect the user? This would be nice for using with ajax requests.

Steps To Reproduce:

yoeunes commented 4 years ago

hi @samuelhgf, thanks for using this package. You could do something like this:

// add a new route to get the notifications from the session:
Route::get('/toastr', 'ToastrController');
<?php

namespace App\Http\Controllers;

class ToastrController
{
    public function __invoke()
    {
        $notifications = session('toastr::notifications', []);
        $max = config('toastr.maxItems') ?: 0;

        return response()->json([
            'options' => config('toastr.options', []),
            'notifications' => array_slice($notifications, -$max),
        ]);
    }
}
// add this snippet of code in your view template
<script type="text/javascript">
$(document).ready(function () {
            $.get('/toastr', function (response) {
                toastr.options = response.options;
                response.notifications.forEach(function (notification) {
                    toastr[notification.type](notification.message, notification.title, notification.options);
                });
            }, 'json');
        });
</script>

can you please confirm if this is working for you ?

yoeunes commented 4 years ago

Screenshot from 2020-03-19 08-37-38 Screenshot from 2020-03-19 08-38-25 Screenshot from 2020-03-19 08-38-37

samuelhgf commented 4 years ago

Hi @yoeunes Thanks for the support!

I fix it by calling the tostar JavaScript method in the ajax response.

Captura de Tela 2020-03-19 às 06 07 50

yoeunes commented 4 years ago

good that you fixed it