Ajax request url point to a route

Asked

Viewed 1,776 times

1

I set 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’ve changed course 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);
        }
    });

But the following mistake happened:

POST http://localhost/manapasteis2/public/%7B%7B%20route(%22productsByCategory%22)%20%7D%7D 403 (Forbidden)
  • I believe it is $.ajax({
 url: "/order/productsByCategory",, the bar at the beginning is to avoid the relative path, if it works let me know

  • which file extension q has the js code?

  • The file is . js even @gmsantos

  • 1

    Killed the riddle! See @Guilhermenascimento’s reply :)

2 answers

2


Use {{ route("apelidoDaRota") }} does not work inside a file .js, and I noticed that you’re using the public instead of setting up the VirtualHost in Apache/Ngnix then 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);
    }
});

Set up in VirtualHost and point directly to the folder public then you’ll just have 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 how to set up VirtualHost:

0

Add an alias:

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

Call by alias:

url: "{{ route("apelidoDaRota") }}",
  • It didn’t work :/ I edited the question with the codes I have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.