I'm new to Laravel and using Ajax for some functionalities.
//Route
Route::post('some/thing/','Controller@Method');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
//controller
public function Method(Request $object){
if(isset($_POST['val1'])){//do something}
}
problem is in the URL parameter of AJAX. When I'm giving value to the url i.e some/thing/, it gives me 404 error showing www.siteurl/some/thing/some/thing/ not found and when I'm keeping url value blank then it's working. But then i don't think it's a good practice to do like this.
I have seperate .js file in public folder. Controller in different and blade file in different directory. Laravel version 5.6.22
thank you.
I think you have to change the Url to the absolute path:
Incase you are working on Blade file:
Change the url from : url: "some/thing/",
To url: {{url('some/thing')}},
In case you are working on external Js File:
Change the url from : url: "some/thing/",
To url: url: "/some/thing/",
Use absolute path instead of relative. append /
before the url like "/some/thing/"
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "/some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With