Himel Biswas
Himel Biswas

Reputation: 1

Ajax success function not working in laravel

My blade view-

@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach

My ajax success function does not work. it doesn't show alert. Therefore I cannot update my database. Here is my ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   },
success: function(data)
                        {
                            alert("ok");        
                        }
  });
});
    }); 

So, Whats wrong with my ajax call? I want to click on link and pass the the id to my controller.

Upvotes: 0

Views: 1498

Answers (3)

Ashik Basheer
Ashik Basheer

Reputation: 1601

Its clearly Laravel's token mismatch error. You should always add error handler to the ajax functions to be sure to see if any error has occurred. There two ways you can get through this error.

Method 1: (recommended)

Add a csrf token in the header as @kacem mentioned

Method 2: Only when you are making an ajax request from a different domain to the laravel server running on a different domain or IP

Go to app/Http/Middleware/VerifyCsrfToken.php and add your POST URLs in the protected variable

protected $except = [
    'post-urls-to-exclude-token-check',
    'multiple-urls',
    'or-wild-cards*
];

Upvotes: 1

kacem
kacem

Reputation: 31

try adding a dataType to your ajax call

    $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    ...
                    dataType: "json",
                    success: function(){

                        ..
                    }
                });

and return a json object from your controller.

return json_encode( $SomeData );

Upvotes: 0

Nirbhay Kularia
Nirbhay Kularia

Reputation: 101

    Add a meta-tag to each page (or master layout):
 <meta name="csrf-token" content="{{ csrf_token() }}">

    And add to your javascript-file (or section within the page):

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

Upvotes: 0

Related Questions