0
votes

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.

3
Are you getting any JS error or Server Error(You can check that in browser console (Ctrl + Shift + i) in Google Chrome???Akshay Khale
I think you might get CSRF Token mismatch ExceptionAkshay Khale
check your error in network tab of developers toolsBalraj Allam
You need to add the ajaxSetup for ajax post requests.Balraj Allam
on developer tools status has shown 500, internal server errorHimel Biswas

3 Answers

1
votes

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*
];
0
votes
    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')
      }
    });
0
votes

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 );