Billy
Billy

Reputation: 2963

How to delete from the database using Ajax with Laravel and Restful Controllers

I have the following code in my view:

@foreach ($articlestore as $art)

<form action="{{URL::to('/story/' . $art->id)}}" method="post" id="article_one">

<div class="form-group">
<input type="hidden" name="chosen_title" value="{{$art->id}}" class="form-control">
</div>
<button type ="button" onclick="deleteArticle({{ $art->id }})" id="Reco">Delete</button>
{{Form::token()}}

</form> 
@endforeach


<script type="text/javascript">

function deleteArticle(id) {

 $.ajax({
 url: '/Project/public/story/'+id,
 data: { "_token": "{{ csrf_token() }}" },
 type: 'DELETE',
 success: function(result) {
 console.log(result);
}
});
}

Controller:

public function destroy($id)
{

     $articledel = FootballArticle::find($id);
             $articledel->delete();


}

Im very new to AJAX and so im struggling to know how to delete a row from my table using JQuery. Any help would be much appreciated.

Upvotes: 1

Views: 4985

Answers (1)

peterm
peterm

Reputation: 92785

Change

<button type ="button" onclick="deleteArticle($art->id)" id="Reco">Delete</button>

to

<button type ="button" onclick="deleteArticle({{ $art->id }})" id="Reco">Delete</button>
                                              ^^          ^^

In deleteArticle() change

url: 'http://localhost/Project/public/story'+id,

to

url: '/Project/public/story/'+ id,
     ^^                   ^^

and add

data: { "_token": "{{ csrf_token() }}" },

so it looks like

$.ajax({
    url: '/project/public/story/' + id,
    data: { "_token": "{{ csrf_token() }}" },
    type: 'DELETE',
    success: function(result) {
        console.log(result);
    }
});

Also you don't need to do a redirect in your destroy() method when you make an ajax call

return Redirect::back();

Upvotes: 3

Related Questions