Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ajax URL issue

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.

like image 624
VPC Avatar asked Sep 12 '25 22:09

VPC


2 Answers

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/",

like image 99
Roland Allla Avatar answered Sep 14 '25 13:09

Roland Allla


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.

like image 43
Romantic Dev Avatar answered Sep 14 '25 11:09

Romantic Dev