How to add ajax url to larvel js file?

I am creating a store locator for a website that I am creating in Laravel. Since the click file calls the js file, tht is in the assests folder. It does not recognize a URL like this

$.ajax({
    url: '{{ URL::action('getLocation') }}',
    // ...
});

This is how I have route.php

Route::post('/getLocation', array('as'=>'getLocation','uses'=>'FrontController@getLocation'));

Therefore, it does not find the file. How can I call this function in ajax url?

+4
source share
6 answers

Here is a demonstration of how I achieved this

Maybe I'll be late. This is just a sample code to help understand the people who visit this question. Hope this helps everyone who visits here.

in my routes.php I define a named route

Route::post('getLocation',array(
    'as'=>'getLocation','uses'=>'FrontController@getLocation')
);

somehtmlform.blade.php

{!! Form::open() !!}
{!! Form::text('input-name',null,array('class'=>'form-control search-input','data-url'=> URL::route("getLocation") ))
{!! Form::close() !!}

my search.js URL- URL

$('.search-input').each(function(){
  $(this).on('change',function (e) {
      search(this)
  });
});

function search(self) {
    var query = $(self).val();
    $.ajax({
        url: $(self).attr('data-url'),
        type: 'post',
        data: {'q':query, '_token': $('input[name=_token]').val()},
        success: function(data){
          console.log(data);        
        },
        error: function(data){
            // Not found
        }
    });
}
+3

, larvel, js .

+2

:

// Add this in your filtes.php file (feel free to store where you like)
View::composer('layouts.master', function($view) {
    $ajaxUrl = json_encode(array('url' => URL::action('getLocation')));
    $view->with('ajax', $ajaxUrl);
});

master.blade.php file (master layout) <head></head> ( js):

<script>var ajax = {{ $ajax or 'undefined' }}</script>

:

// ajax.url
console.log(ajax.url);

.

+1

, URL-. URL::action() URL::route().

URL::action() URL- , :

URL::action('FrontController@getLocation')

URL:: route() URL- , , "as" = > "routeName". :

URL::route('getLocation')

, !

0

ajax .js ,
'{{ URL::action('getLocation') }}' '/getLocation'
URL-, : 'http://domain.com/getLocation', .

0

js , Url:: action

url:"/getLocation"
Hide result
0

Source: https://habr.com/ru/post/1531841/


All Articles