Reputation: 15
I have a few functions in one controller, for example:
public function cruise($id){...}
public function block($id){...}
In web.php I added routes:
Route::post('/profile/{cruise}', 'UtilityController@cruise');
Route::post('/profile/{block}', 'UtilityController@block');
In my ajax in blade:
function block() {
$.ajax({
type: 'POST',
url: "{{route('profile', $user->id)}}", // PROBLEM HERE
dataType: 'JSON',
data: {formData: $data},
success: function ($data) {
console.log('status = ' + status);
},
error: function (json) {
console.log(json);
},
})
}
How can I define specific function route from my controller in ajax?
Upvotes: 1
Views: 353
Reputation: 15047
The problem is that you have the same route for 2 different controller methods
Route::post('/profile/{cruise}', 'UtilityController@cruise');
Route::post('/profile/{block}', 'UtilityController@block');
When you write Route::post('/profile/{cruise}',...
this part {between_curly_braces}
is a wildcard.... in other words it's just the name of the variable that laravel will assign the value you are sending...
In your case it's $user->id
and whatever you do it will always hit the first route in your routes file that corresponds that structure post('/profile/{ }
In order for this to work so you can hit different methods in your Controller you will have to separate the routes to hit different methods. Make these 2 Routes in routes file:
Route::post('/profile-cruise/{cruise}', 'UtilityController@cruise')->name('profile.cruise');
Route::post('/profile-block/{block}', 'UtilityController@block')->name('profile.block');
and in ajax functions hit the wanted routes something like:
function cruise() {
$.ajax({
type: 'POST',
url: "{{route('profile.cruise', $user->id)}}",
dataType: 'JSON',
data: {formData: $data},
success: function ($data) {
console.log('status = ' + status);
},
error: function (json) {
console.log(json);
},
})
}
and for cruise:
function block() {
$.ajax({
type: 'POST',
url: "{{route('profile.block', $user->id)}}",
dataType: 'JSON',
data: {formData: $data},
success: function ($data) {
console.log('status = ' + status);
},
error: function (json) {
console.log(json);
},
})
}
Upvotes: 1