jeudi 2 mai 2019

Why is it so damn hard to post a variable to a Laravel 5 route from javascript?

I'm trying to send a simple notification id from javascript on click, to mark a notification is read.

I've spent hours on it, but I get an endless 500 server error "The GET method is not supported for this route. Supported methods: POST."

Can anyone explain what I'm doing wrong???

My javascript looks like this

    $(".read-notification").on("click", function (e) {

        if ($(this).hasClass('unread')) {
            var mainDiv = $(this).closest(".notification");
            var divId = $(mainDiv).attr("id");
            var notificationId = divId.replace("notification-", "");

            document.getElementById("notificationIcon-"+notificationId).innerHTML = "<i class=\"far fa-envelope-open fa-2x\"></i>";
            $(this).removeClass('unread');
            $(this).addClass('read');
            $('.collapse').collapse('toggle');


            $.ajax({
                type: 'post',
                url: 'markAsRead',
                data: {'notificationId' : notificationId},
                dataType: 'json',
                success: function(response){
                    console.log("That worked!");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });


  //          $(".read-notification").attr("action", "/" + notificationId + "/markAsRead");
      }
    })

My route like this

Route::post('markAsRead', 'NotificationController@markAsRead');

and my controller like this

    public function markAsRead(Request $request) {

        $user = \Auth::user();
        $notification = $user->notifications()->where('id', $request->notificationId)->first();
        if ($notification) {
            $notification->markAsRead();
            return back();
        } else {
            return back()->withErrors('Sorry, we had a problem');
        }

    }

but at the moment I can't get passed the route.

I've tried named routes and urls, but I always get the same error.

Any help much appreciated...



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IUXGJJ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire