hfingler
hfingler

Reputation: 2004

jQuery ajax request returning 405 ( POST not allowed) in laravel app

I can't seem to figure this out. Is this an apache configuration? I've seen some filters.php configurations to add POST but if this was the problem it would be somewhere in laravel docs, right?

Routes:

Route::get('orders/add', 'OrderController@add');
Route::resource('orders', 'OrderController');

Controller (REST methods are empty):

class OrderController extends \BaseController {
   public function add()
    {
       if (Request::ajax())
           return "ajax request ";
       else 
           return "not ajax";
    }
...

jQuery:

function add()
{
   var tid = $('#sites input[type=radio]:checked').attr('id');

   $.ajax({
      type: "POST",
      url: 'add',
      data: { tid: tid }
   }).done( function (msg){
      alert(msg);
   });
}

Button to send:

<button onclick="add()" id="formSubmit"> Carrinho </button>

And the error firefox shows me on console when I click the button:

POST http://localhost/orders/add [HTTP/1.0 405 Method Not Allowed 17ms]

Thank you all.

Upvotes: 0

Views: 9924

Answers (2)

bgallagh3r
bgallagh3r

Reputation: 6086

You really don't need a /add route if you are using a resource controller as it has a create method on it already.

OrdersController extends BaseController {
    public function index() {} // show ALL orders
    public function create() {} // show the form to create an order aka "add"
    public function store() {} // get input from post.
    public function update($order_id) {} // update an order resource 
    public function destroy($order_id) {} // destroy an order resource
}

In your ajax change the url to url: {{URL::route('orders.store')}}, and that should fix it.

Upvotes: 1

Mysteryos
Mysteryos

Reputation: 5791

Route::get expects a GET HTTP header. U'll need to use Route::post.

Instead of

Route::get('orders/add', 'OrderController@add');

you should use

Route::post('orders/add', 'OrderController@add');

Source: Laravel routing documentation

Upvotes: 4

Related Questions