Skip to content
Advertisement

Passing 2 parameters in ajax url in Laravel route

I need help, my ajax request doesn’t work if i use 2 parameters in url

--- AJAX---
url: "/post/"+post_id+"/"+vote, 
--- ROUTE ---
Route::get('/post/{id}/{up_or_down_vote} 

but if i only use 1 parameter

--- AJAX---
url: "/post/"+post_id 
--- ROUTE ---
Route::get('/post/{id}

it works perfectly fine.

There isn’t error in the first one but i think it does not reach to the controller because the output in response is undefined.

this is my view

this is my ajax request

when i clicked the vote i alerted it to check if the url is correct and it is

this is the response, the json should be here

This is the controller

Advertisement

Answer

First off, avoid images that show only code in your question. It’s much better if you type it out here. Now this is how you can solve your issue.

In your route, give it a name, so you can access it via the route() method as such: Route::get('/post/{id}/{up_or_down_vote}', [YOUR CONTROLLER HERE::class, 'vote'])->name('post.updown');

Replace YOUR CONTROLLER HERE with your controller(because I don’t know the name of your controller as you did not mention it above).

Now in your ajax code just before the $.ajax(, add a url variable as such:

let url = {{ route('post.updown', ['id' => ':post_id', 'up_or_down_vote' => ':vote']) }};
url = url.replace(':post_id', post_id);
url = url.replace(':vote', vote);

Now that you have a variable containing the url, just pass it to your ajax request as such:

url : url,

And this should work!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement