2
votes

I have a problem with Laravel and POST request. My route is defined as POST and method used in AJAX is POST but it keeps sending GET requests. If I change route to undefined route then it sends POST, but if I aim to this route defined as POST it sends GET request.

AJAX:

$.ajax({
    method: "POST",
    url: "{{ url('admin/rentacar/save_availability_for_d') }}",
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    data: $(form).serialize(),
    dataType: "json",
    success(result){
        //
    }
});

Route is defined as:

Route::post('save_availability_for_d', [
    'as' => 'save_availability_for_d', 
    'uses' => 'RentacarController@saveCarAdjustment'
]);

CSRF token is included in meta tags:

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

This is what happens in console when I try to send AJAX request:

XHR finished loading: GET "http://www.carsrental.me/public/me/admin/rentacar/save_availability_for_d".

and this is what happens if I append just one random character at the end to aim for route that doesn't exists

XHR failed loading: POST "http://www.carsrental.me/public/admin/rentacar/save_availability_for_dd".
3
You might want to take a look at the api routes. Making the url /api/admin/rentacar/save_availability_for_d. It's not the solution but it's a lot cleaner.SuperDJ
That would only be the case if it's defined the api routes @SuperDJ, otherwise it makes no difference.ollieread

3 Answers

8
votes

This might not be a Laravel thing. I've seen this happen if the server-configuration is a little off. What was happening was the site was set to be https, and the Apache config was set to redirect http, port 80, requests over to port 443. But in the process, it was losing track of the request-method (and the GET arguments).

Not certain this is your exact problem, that's kind of an all-or-nothing thing. But it might be worth a look.

3
votes

As @Claymore has pointed out in the answer above, it's almost always how your server is configured and how you call the API/route. If server is configured to only allow https(port 443) requests, any http(port 80) POST request will be redirected to https by the server and received as a get request. This was my main problem because we had recently installed ssl certificates and didn't change the API call protocol from our mobile app, which resulted in failed/undesired requests.

1
votes

Try this and also don't forget to clear the cache

$.ajax({
      url: '{{route('save_availability_for_d')}}',
      dataType: 'json',
      type: 'POST',
      data: $(form).serialize(),
      success: function (result) {
      }
});