I am building a store locator for a website that I am building in Laravel. Since the blade file calls the js file tht is on the assests folder. It doesn't recognize the URL like this
$.ajax({
url: '{{ URL::action('getLocation') }}',
// ...
});
This is how I have my route.php
Route::post('/getLocation', array('as'=>'getLocation','uses'=>'FrontController@getLocation'));
So it doesn't find the file. How can I call this function in the ajax URL?
To use AJAX in Laravel, you need to import a jquery library in your view file to use ajax functions of jquery, which will be used to send and receive data using ajax from the server.
AJAX is not a programming language. AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)
The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .
Here is a demonstration of how i would achieve this
I might be late here. This is just a sample code to help understand people who visit this question. Hope this helps anyone who visits here.
in my routes.php i define a named route
Route::post('getLocation',array(
'as'=>'getLocation','uses'=>'FrontController@getLocation')
);
added name route as data-url in my somehtmlform.blade.php file
{!! Form::open() !!}
{!! Form::text('input-name',null,array('class'=>'form-control search-input','data-url'=> URL::route("getLocation") ))
{!! Form::close() !!}
my search.js file catches the data-url and use it as post 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
}
});
}
You can use this package, it gives almost all laravel helper functions which can be used in js files too.
You may try this:
// 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);
});
Add this in you master.blade.php
file's (master layout
) <head></head>
section (place it before your js
file):
<script>var ajax = {{ $ajax or 'undefined' }}</script>
Now you can use this as:
// ajax.url
console.log(ajax.url);
Read here, similar thing.
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