I just started learning Laravel 5.5 to explore a much "advanced" framework. I have worked using Codeigniter and loved it. Now I am implementing a small CRUD functionality and it works fine. Now I am trying to use Jquery AJAX so it doesn't have to refresh. I have used Jquery AJax before on my previous codeigniter projects. Now when I try it using Laravel, it just does't work. I have checked many references, but I am not sure why its not succeeding. I am trying to implement it to the Delete function, if I have that working, I'm sure I can do the rest.
THE PROBLEM:
return response ()->json ($post);
But yes the item deletes. How I want it to be
Controller
public function destroy($id)
{
$post = Post::find($id);
if (auth()->user()->id !== $post->user_id){
return redirect ('/posts')->with('error', 'Unauthorized page');
}
$post->delete();
return response ()->json ($post);
}
Routes
Route::resource('posts','PostsController');
View
{!!Form::open(['action'=>['PostsController@destroy', $post->id], 'method'=>'POST', 'class'=>''])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::button('Delete', ['type' => 'submit', 'class' => 'btn btn-danger delete','id' => 'delete', 'data-id' => $post->id ] )}}
{!!Form::close()!!}
JS
<script type="text/javascript">
$(document).ready(function(){
$(".delete").on('click',function(event){
var id = $(this).attr('data-id');
alert(id);
$.ajax({
url: "posts/"+id,
type: "DELETE",
success: function(){
alert("DELETED");
}
});
});
});
</script>
Thank you so much friends!!
The issue is that you are submitting the form before firing away your REST
call, so your rest call never gets off, but the page reloads, because the form has been submitted and you then show the json which you returned from your controller.
Solution
Remove your Form
in the blade view. Then update ajax as this:
$(document).ready(function() {
var id = {!! $post->id !!};
$.ajax({
url: "posts/"+id,
type: "DELETE",
contentType: 'application/json',
success: function(data) {
console.log(data);
alert("DELETED");
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.