Home Simple Ajax in Laravel
Reply: 0

Simple Ajax in Laravel

user1986
1#
user1986 Published in June 20, 2018, 1:30 am

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

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

© 2016 Powered by mzan.com design MATCHINFO