Simple Ajax in Laravel

In a Laravel app, I need to update some data in the database after a button is clicked, without reloading the page, thus requiring ajax. No data needs to parsed, only a function in one of the controllers should be invoked, so it's the simplest kind of ajax request.

Based on this example, I set up the following, but nothing happens. No error, no response from the check alert('success!'), nothing.


QUESTION: why does nothing happen? Could it be that the Javascript is not recognized at al?


Head

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Routes - web.php

Route::post('/notificationsSeen','NotificationController@seen');

Controller - NotificationController.php

public function seen() {
    $userNotifications = Notification::where('user_id',Auth::id())
                    ->where('status','new')
                    ->update(array('status' => 'seen'));

    return;
}

View

<button type="button" id="notifications"></button>

<script>
  $("#notifications").on('click', function() {
    $.ajax({
       type:'POST',
       url:'/notificationsSeen',
       data:'_token = <?php echo csrf_token() ?>',
       success:function(data){
          alert('success!');
       }
    });
  });
</script>

EDIT: WORKING SOLUTION

Change the contents of the box above labeled "View" to the following:

<button type="button" id="notifications"></button>

<script>
  (function ($) {
        $(document).ready(function() {

            $('#notifications').on('click', function() {

            $.ajax({
                url: '/notificationsSeen',
                type: 'POST',
                data: { _token: '{{ csrf_token() }}' },
                success:function(){alert('success!');},
                error: function (){alert('error');}, 
            });

            });

        });
        }(jQuery));
</script>

Upvotes: 1

Views: 5001

Answers (2)

parker_codes
parker_codes

Reputation: 3397

In your AJAX request, data is not a string. It is a key value pair. So use

data: { _token: '{{ csrf_token() }}' }

Upvotes: 2

YouneL
YouneL

Reputation: 8369

You shouldn't pass the csrf token like this:

data:'_token = <?php echo csrf_token() ?>',

You have to store it in a HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then automatically add the token to all request headers:

$( document ).ready(function() {

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $("#notifications").on('click', function() {
        $.ajax({
            type:'POST',
            url:'/notificationsSeen',
            data: {status: 'seen'},
            success:function(data){
                alert('success!');
            }
        });
    });

});

Controller:

public function seen() {
    $userNotifications = Notification::where('user_id',Auth::id())
                    ->where('status','new')
                    ->update(array('status' => request()->input('status')));

    return ['success' => true];
}

Upvotes: 0

Related Questions