最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Laravel error 405(Method Not Allowed) Ajax Posting - Stack Overflow

programmeradmin0浏览0评论

Hello i wnat to send my data with ajax to my controller.

My CODE

AJAX

  $.ajax( {
    type:'POST',
    header:{
      'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    },
    url:"{{route('race.post')}}",
    data:{
      _token: "{{ csrf_token() }}",
      dataType: 'json', 
      contentType:'application/json', 
    }


})
.done(function() {
    alert('success');
})
.fail(function() {
    alert("error");
});

CONTROLLER

 public function Points(Request $request){
    $test = $request->input('data');
    return "$test";
}

ROUTE

Route::post('updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']); 

And there are the errors what i get.

Console

Network-preview

Network-Response

Hello i wnat to send my data with ajax to my controller.

My CODE

AJAX

  $.ajax( {
    type:'POST',
    header:{
      'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    },
    url:"{{route('race.post')}}",
    data:{
      _token: "{{ csrf_token() }}",
      dataType: 'json', 
      contentType:'application/json', 
    }


})
.done(function() {
    alert('success');
})
.fail(function() {
    alert("error");
});

CONTROLLER

 public function Points(Request $request){
    $test = $request->input('data');
    return "$test";
}

ROUTE

Route::post('updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']); 

And there are the errors what i get.

Console

Network-preview

Network-Response

Share Improve this question asked Mar 7, 2019 at 9:13 PatrikPatrik 511 gold badge1 silver badge5 bronze badges 4
  • I think You have separate .js file for ajax. that's why your route and csrf_token is not working. – ThataL Commented Mar 7, 2019 at 9:48
  • That's true i have separetad js file for ajax. – Patrik Commented Mar 7, 2019 at 9:49
  • Thats why it is not working. for csrf_token use meta tag. and for url pass url as parameter to javascript onclick, or Onchange function. can i see your .js fiile when the ajax will call.. – ThataL Commented Mar 7, 2019 at 9:52
  • try my answer as below. I have changed the code by comparing previous and current question of you. – ThataL Commented Mar 7, 2019 at 10:05
Add a comment  | 

9 Answers 9

Reset to default 8

I just removed the slash at the end of url and it began working... /managers/games/id/push/ to:

$http({
  method: 'POST',
  url: "/managers/games/id/push",

add this one in your layout.blade file

<meta name="csrf-token" content="{{ csrf_token() }}">

then use this one in your js code

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

i hope this will help!!

First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.

routes/web.php

Route::get('ajaxRequest', 'RacesController@Points');

Route::post('ajaxRequest', 'RacesController@Points');

Include this meta tag inside your view

<meta name="csrf-token" content="{{ csrf_token() }}" />

Include javascript code inside your ajax call

$.ajaxSetup({

    headers: {

        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

    }

}); 

Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.

Try to change the url to this:

url: '/updateC'

When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.

I have different way to use it: AJAX

data = {
        selectmanufacturer: selectmanufacturer,
        categories: selectCategory,
        _token: "{{csrf_token()}}",
        productName: productName
      };
     $.ajax({
        url: '{{URL::to('/all-products-data')}}',
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function (response) {
        },
          error: function (response) {
            alert(response);
          }
        });

Controller:

public function Points(Request $request){
    $test = $request->all();
    return "$test";
}

I hope It will be helpful to you

The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:

url:"{{route('race.post')}}"

But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.

You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.

not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link HTML code

<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>

Updated Code

function onBtnClick(){
    var token = $('meta[name="csrf-token"]').attr('content');
    var url = $(this).attr("data-url");    
    $.ajax( {
        method:'POST',
        header:{
          'X-CSRF-TOKEN': token
        },
        url: url,
        data:{
          _token: token,
          dataType: 'json', 
          contentType:'application/json', 
        }        
    })
    .done(function() {
        alert('success');
    })
    .fail(function() {
        alert("error");
    });
}

Check if your laravel route is correctly set for this request. In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController@uploadCropImage'); But the request was sent to http://127.0.0.1:8000/news/crop-image-upload So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController@uploadCropImage');

So, in your case, try to add a literal url on ajax like this:

url:"/races/updateC"

and add 'races/' in the route like this:

Route::post('/races/updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']); 
        $.ajax({
            url: `***/****/`,
            type: "POST",
            cache: false,
            data: {
                "title": title,
                "content": content,
                '_token': '{{ csrf_token() }}',
                '_method': 'PUT',
            },
            success: function(response) {},
            error: function(error) {}
        });

OR

<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
发布评论

评论列表(0)

  1. 暂无评论