Wednesday, March 29, 2017

Laravel Ajax cannot update database when click on a link

I have an audio file on public folder like this-

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

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

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

My Route:

Route::post('/update_download_count', 'PagesController@updateDownloadCount');

Controller:

public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?



via Himu

Advertisement