newOne
newOne

Reputation: 21

Call laravel route from js file

I'm working with Laravel 5 for the first time, i have a blade where i include a JS file, when the blade calls the JS file. It doesn't recognize the URL : this is how i call my URL in JS file :

 $.ajax({
        type: "POST",
        cache: false,
        url : "{{URL::to('zone')}}",
        data: {'ma':$('select[name=ma]').val()},
        success: function(data) {
            ...
        }
    });

When i include this code in myBlade.blade.php it works fine but from the JS file i got the 403 error

Upvotes: 2

Views: 21303

Answers (2)

sbedulin
sbedulin

Reputation: 4342

Blade doen't process JavaScript files, only those with blade.php extension

Solution may be to provide a global configuration object with a collection of routes you are interested in.

Assuming you have two separate files: index.blade.php plus main.js

1) index.blade.php

<script>
    // global app configuration object
    var config = {
        routes: {
            zone: "{{ URL::to('zone') }}"
        }
    };
</script>
<script src="main.js"></script>

2) main.js

$.ajax({
    type: "POST",
    cache: false,
    url : config.routes.zone,
    data: {'ma':$('select[name=ma]').val()},
    success: function(data) {
        ...
    }
});

Upvotes: 18

Manmeet Khurana
Manmeet Khurana

Reputation: 377

In Laravel And Also In codeigniter simple Approch is
get the Base Url Path
Here I user

//code here
var path = {!! json_encode(url('/')) !!}

$.ajax({
    type: "POST",
    cache: false,
    url : path+'/zone',
    data: {'ma':$('select[name=ma]').val()},
    success: function(data) {
        ...
    }
});

Upvotes: 3

Related Questions