简体   繁体   中英

(Laravel + Ajax) The url is wrong and AJAX is not working

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?

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM