Url Ajax request pointing to a laravel route

1

I configured the following route in my route file:

Route::post('order/productsByCategory', ['uses'=>'OrderController@productsByCategory']);

How do I use it in my Ajax request?

$.ajax({
        url: "",
        type: 'POST',
        data: "",
        headers: {
            'X-CSRF-Token': laravel_token
        },
        dataType: 'JSON',
        success: function (data) {
            console.log(data);
        }
    });

EDIT : I changed the route to:

Route::post('Order/productsByCategory', ['as' => 'productsByCategory', 'uses'=>'OrderController@productsByCategory']);

And the requisition for:

$.ajax({
        url: '{{ route("productsByCategory") }}',
        type: 'POST',
        data: { id: categoryId},
        dataType: 'JSON',
        headers: {
            'X-CSRF-Token': laravel_token
        },
        success: function (data) {
            debugger;
            console.log(data);
        }
    });

However, the following error occurred:

POST http://localhost/manapasteis2/public/%7B%7B%20route(%22productsByCategory%22)%20%7D%7D 403 (Forbidden)
    
asked by anonymous 27.03.2017 / 03:45

2 answers

2

Using {{ route("apelidoDaRota") }} does not work inside a .js file, and I noticed that you are using public instead of setting VirtualHost in Apache / Ngnix so you will have to do so:

$.ajax({
    url: '/manapasteis2/public/order/productsByCategory',
    type: 'POST',
    data: { id: categoryId},
    dataType: 'JSON',
    headers: {
        'X-CSRF-Token': laravel_token
    },
    success: function (data) {
        debugger;
        console.log(data);
    }
});

If you set it to VirtualHost and point directly to the public folder then you only need to do this:

$.ajax({
    url: '/order/productsByCategory',
    type: 'POST',
    data: { id: categoryId},
    dataType: 'JSON',
    headers: {
        'X-CSRF-Token': laravel_token
    },
    success: function (data) {
        debugger;
        console.log(data);
    }
});

Here are some tips on setting VirtualHost :

27.03.2017 / 04:11
0

Add an alias:

Route::post('order/productsByCategory', ['as' => 'apelidoDaRota', 'uses'=>'OrderController@productsByCategory']);

Call by alias:

url: "{{ route("apelidoDaRota") }}",
    
27.03.2017 / 03:47