How do I add ajax URL on a laravel js file? - ajax

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?

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.

It looks like you're using the wrong method for generating the URL.
Try switching from URL::action() to URL::route().
URL::action() is used to generate a URL to a given controller action, but then you need to write it like this:
URL::action('FrontController#getLocation')
URL::route() generates a url to a route which is named in the route definition, using "as" => "routeName". In your case:
URL::route('getLocation')
Hope this helps!

If you call your ajax function from a .js file,
try to change the blade part '{{ URL::action('getLocation') }}' to '/getLocation'
or pass a full url like: 'http://domain.com/getLocation' and it should work.

in js file, you can't not use the Url::action for route
just do
url:"/getLocation"

Related

laravel passing a variable to js file from a controller

I have a js file located in assets folder (not View). can i pass a varible from a controller?
In view file:
The Js is called like this
<canvas id="chart1" class="chart-canvas"></canvas>
</div>
It is not possible (in my point of view) to put a variable to external JS file. You can use data-... attributes and get values from html elements.
For example you can pass your PHP variable as a json encoded string variable in your controller.
$data['chart_info'] = json_encode($chart_info);
return view('your_view', $data);
Then put it in data-info like this.
<canvas id="chart1" class="chart-canvas" data-info="{{ $chart_info }}"></canvas>
And finally in JS, you can get the variable and decode (parse) it as following.
let canvas = document.getElementById('chart1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
You can put that part of the Javascript in the view and send the variable to the same view. For example, add a section in view:
#section('footer')
<script type="text/javascript">
</script>
#endsection
Do not forget that you should add #yield('footer') to the end of your layout view.
I don't like to mix javascript and PHP/Blade, it might be hard to read the code in the future... You could use a different approach, loading the chart with a async ajax request.
You will have to create a end-point that returns the data you need for your chart:
Your router:
Route::get('/chart/get-data', [ ControllerName::class, 'getChartData' ]);
Your controller method:
public function getChartData() {
$chartData = [];
// Your logic goes here
return $chardData;
}
In your javascript (using jquery) file there will be something like that:
function loadChartData() {
$.ajax({
'url': '/chart/get-data',
'method': 'GET'
})
.done((data) => {
// Load your chart here!!!
})
.fail(() => {
console.log("Could not load chart data");
});
}
Hope I helped ;)

Calling MVC Controller method with Ajax call not working [duplicate]

I been trying to use #Url.Action inside Ajax url in another external .JS file but unfortunately i got no luck.
Here's my Code:
$.ajax({
type: 'post',
url: "#Url.Action("ClearData","Home")",
success: function () {
}
});
This Code working only inside the View itself but not in Javascript externally.
Iv'e been searched some possible solution but it seems different than this.
Is there any alternative way to use #Url.Action in another .Js File?
#Url.Action() is razor (server side) code and is not parsed in external files. Options include
Declaring a global variable in the main file, say
var url = #Url.Action("ClearData","Home");
and then in the external script use url: url in the ajax call
Including a data- attribute in the element your handling, for example if its a button click event, then
<button data-url="#Url.Action("ClearData","Home")" id="mybutton">
and then reading that value in the external file, for example
$('#mybutton').click(function() {
var url = $(this).data('url');
$.ajax({
url: url,
....
if your js code inside view
$.ajax({
type: 'post',
url: "#Url.Action("ClearData","Home")",
success: function () {
}
});
this is work
when js code is an separate (external file)
#Url.Action("ClearData","Home") is not work ,
this case you have to write total url or folder path
You can create a partial view, then inside this view are just list of hidden fields
such as
#Html.Hidden("ActionName", #Url.Action("ActionName", "Controller"))
which generates this
<input id="ActionName" name="ActionName" type="hidden" value="/controller/ActionName">
then you can call it like
var urlAction = $('#ActioName').val();
or you can create a js function like what I did
function ActionCaller(actionName)
{
return $('#' + actionName).val();
}
var action = ActionCaller(ActionName);

Cannot return a laravel download via ajax call

I want the user to download a file and it doesn't really need to be via ajax, but it was the easiest way I found, but it's not working.
Here is my method from the Controller that I'm calling:
public function download(Request $request)
{
$dir = $request->get("directory");
return response()->download($dir);
}
Here is my ajax function:
function download(diretorio) {
$.ajax({
url: "/panel/download",
data: {_token: jQuery(".token").val(), diretorio: diretorio},
success: function(e) {
}
}).done(function(e) {
});
}
This function is being called inside this append:
$('#uploads tbody').append("<tr><td>" + fileName + "</td> <td><a class='btn btn-success' href='' onclick=\"download('" + item + "')\">Download</button></td></tr>");
});
Here is my route, which is inside a group called panel:
Route::get('/download/', ['as' => 'files.download', 'uses' => 'Panel\ClientController#download']);
My first question is: Is it possible to make this call from ajax to a download response from laravel?
Second question: I cannot figure out how to replace the ajax call for a route to a laravel controller, is it possible?
Thank you!
Yes it is possible. This is just with Laravel only though. Try this example:
HTML: (just call your GET route here)
download file(s)
Download Function
public function download()
{
// $pathToFile : set to what you need
return Response::download($pathToFile);
}
due to the fact that the directory path parameter has slashes, I think the route is expecting other parameters. So I decided not to pass the entire directory path, but only an ID and the name of the file. So my route became like this: Route::get('/download/{id}/{fileName}', ['as' => 'files.download', 'uses' => 'Painel\ClienteController#fazerDownload']);
And it worked. Thank you for the answers and efforts!

How can I put in a laravel route in a js file

I have my javascript code in a js file that I include in my main layout.
I want to call ajax, to a specific named route. Becuase it is a js file, the blade syntax can't be run from there.
I tried writing out the url, but the url changes depending on the route that is calling the ajax, so it's not pointing to the correct folder.
I'd rather use a names route.
Any other suggestions?
Have you considered writing out all the named routes you'll need into the view? Perhaps make a hash of routes and just make the ajax call to the one you need at the time. Something like:
var routes = {
'first': '{{ route('first') }}',
'second': '{{ route('second') }}',
// ....
};
// Somewhere later in code
$http.get(routes.second).then(function(result) {
// do something
});
In your view file, define a global JavaScript variable:
<script>
var globalRouteName = "{{ $route }}";
</script>
And now, in your js file, simply use globalRoutName as variable.

Wordpress FrontEnd Ajax return 0 using Theme

Hi I know this has been asked a few times but I have been through every answer and tried them all with no luck.
I am trying to use Ajax in a Wordpress front end page, I have security in the page to ensure the user is logged in before they can view this page too.
No matter what code i enter my ajax call always returns 0.
function ajaxfoodlookup()
{
echo "ajax fired";
die();
}
add_action('wp_ajax_nopriv_ajaxfoodlookup','ajaxfoodlookup');
add_action('wp_ajax_ajaxfoodlookup','ajaxfoodlookup');
This is what I have in my functions.php (i have also tried exit(); and die($results) where $results = 'ajax fired'; nothing seems to work.
This is what I have in the page to call the ajax;
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: { action:'ajaxfoodlookup'},
success: function (data) { alert(data);}
});
The only thing that I have different to the other questions/answers on here is that I am using a bought Theme which does have some code added, is that theme able to hijack my ajax calls? I thought wordpress would execute the ajax call depending on the 'action' in the data supplied?
Please help its driving me crazy?
Thanks
Official WordPress recommendation is to use the ajaxurl variable instead of hard coded one. Insert this before your JS code and change the url of your jQuery.ajax to use ajaxurl.
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
You can also use wp_localize_script to define the ajaxurl

Resources