Home Simple Ajax in Laravel
Reply: 2

Simple Ajax in Laravel

Michiel van Nesselrooij
1#
Michiel van Nesselrooij Published in 2018-01-12 17:41:02Z

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

  (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));
GoogleMac
2#
GoogleMac Reply to 2018-01-12 18:24:49Z

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

data: { _token: '{{ csrf_token() }}' }
YouneL
3#
YouneL Reply to 2018-01-12 18:01:13Z

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];
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334163 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO