Reputation: 71
Here is my code in blade i wanna trying to click button, then send the id to the controller with AJAX.
<input type="button" onclick="javascript:del_click({{$leftnew->id}});" style="background-image:url(img/delete.jpg);background-size:cover;width:5px;height:12px; border:none; line-height:0;text-indent:-9999px; ">
AJAX part
function del_click(data){
//alert(data);
var request = new XMLHttpRequest();
$.ajax({
type :"POST",
url :"{{url('/deleteNews')}}}",
dataType:"json",
data :{ data:data },
success :function(response) {
alert("thank u");
},
error: function(e) {
console.log(e.responseText);
}
});
Route.php
Route::post('deleteNews','NewsController@deleteNews');
Controller
public function deleteNews(Request $request){
$news_id = $request->news_id;
$news= NewstbEloquent::find($news_id);
if($news->delete()){
return redirect('/')->with('msg','success');
}
else{
return redirect('/')->with('msg','error');
}
}
when i clicked the button, it will get the response with....
http://localhost/YangMing567/public/deleteNews%7D
i have no idea. what happened? why there get the "%7D"? i didnt set that in the url, and it got the response with the %7D back.
it look like not pass the route page, then get the error because of the URL wrong. Have anyone know the reason?
Upvotes: 0
Views: 675
Reputation: 875
You have extra }
in url. Remove it.
{{url('/deleteNews')}}
Also you need to add CSRF too. Otherwise you will get HttpException.
Add this meta to head
tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
And before ajax request add this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So your script must be:
<script>
function del_click(data){
//alert(data);
var request = new XMLHttpRequest();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type :"POST",
url :"{{url('/deleteNews')}}",
dataType:"json",
data :{ data:data },
success :function(response) {
alert("thank u");
},
error: function(e) {
console.log(e.responseText);
}
});
}
</script>
Upvotes: 1