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

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.

Related

How to pass javascript variable from laravel controller to vuejs component

I'm trying to build a page on Laravel 5.4 which contains few data which needs to be manipulated and then sent across the views. My view contains components of the vuejs v2.0. I want those data to be implemented in the components. I tried using the laracasts PHP Vars to JS transformer but unable to get it. I followed the steps by placing "laracasts/utilities": "~2.0" in my composer.json then I added the serviceprovider as mentioned in the documentation, I published the vendor and added the following in config/javascript.php,
'bind_js_vars_to_this_view' => 'Nitseditor.show',
I'm having a dynamic views folder which is currently inside my Nitseditor\home\resources\views Now in my controller I'm having following codes:
public function show()
{
JavaScript::put([
'foo' => 'bar',
'age' => 29
]);
return view(Nitseditor.show);
}
Now first of all it was throwing an error as I see that it was including use MongoDB\BSON\Javascript; then I removed and tried using use JavaScript
Now in the app.js file which is present in my asset folder, I'm including each components and trying to do console.log(foo); but its throwing an error foo not defined.
There are a few ways to do this depending on what you are trying to achieve and how your project is set up. The simplest way is to make a request to your controller from inside your component that returns json. Laravel 5.4 comes with axios so you can use that:
methods: {
getData(){
axios.get('/controller/route')
.then(response => {
// set your variables from the response
this.myData = response.data;
})
.catch(error => {
console.log(error);
});
},
data(){
return {
myData: {}
}
}
If you need child components to access the data then you would need to put that in the parent and pass myData" using props.
You could also create a directive and pass your variable down directly from your blade template:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
});
Then you would just need to do:
<div v-init:vars="{foo: 'foo', age: 29}"></div>
And pass vars as props to any component that needs them:
Here's the JSFiddle: https://jsfiddle.net/3e05qwLh/
If you have multiple descendants that rely on your variables you will probably want to look at using vuex.
Dunno if it helps but I use this method for passing variables to javascript:
// in master layout (head section)
<meta name="foo" content="{{ $foo }}">
// in javascript (included or in the template)
foo = $('meta[name=foo]').attr('content');
If you have javascript in the blade template you can use directly this method:
foo = "{{ $foo }}";

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

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"

JavaScript code in view issue in Laravel

I put JavaScript code in a view file name product/js.blade.php, and include it in another view like
{{ HTML::script('product.js') }}
I did it because I want to do something in JavaScript with Laravel function, for example
var $path = '{{ URL::action("CartController#postAjax") }}';
Actually everything is work, but browser throw a warning message, I want to ask how to fix it if possible.
Resource interpreted as Script but transferred with MIME type text/html
Firstly, putting your Javascript code in a Blade view is risky. Javascript might contain strings by accident that are also Blade syntax and you definitely don't want that to be interpreted.
Secondly, this is also the reason for the browser warning message you get:
Laravel thinks your Javascript is a normal webpage, because you've put it into a Blade view, and therefore it's sent with this header...
Content-Type: text/html
If you name your file product.js and instead of putting it in your view folder you drop it into your javascript asset folder, it will have the correct header:
Content-Type: application/javascript
.. and the warning message will be gone.
EDIT:
If you want to pass values to Javascript from Laravel, use this approach:
Insert this into your view:
<script type="text/javascript">
var myPath = '{{ URL::action("CartController#postAjax") }}';
</script>
And then use the variable in your external script.
Just make sure that CartController#postAjax returns the content type of javascript and you should be good to go. Something like this:
#CartController.php
protected function postAjax() {
....
$contents = a whole bunch of javascript code;
$response = Response::make($contents, '200');
$response->header('Content-Type', 'application/javascript');
....
}
I'm not sure if this is what you're asking for, but here is a way to map ajax requests to laravel controller methods pretty easily, without having to mix up your scripts, which is usually not the best way to do things.
I use these kinds of calls to load views via ajax into a dashboard app.The code looks something like this.
AJAX REQUEST (using jquery, but anything you use to send ajax will work)
$.ajax({
//send post ajax request to laravel
type:'post',
//no need for a full URL. Also note that /ajax/ can be /anything/.
url: '/ajax/get-contact-form',
//let's send some data over too.
data: ajaxdata,
//our laravel view is going to come in as html
dataType:'html'
}).done(function(data){
//clear out any html where the form is going to appear, then append the new view.
$('.dashboard-right').empty().append(data);
});
LARAVEL ROUTES.PHP
Route::post('/ajax/get-contact-form', 'YourController#method_you_want');
CONTROLLER
public function method_you_want(){
if (Request::ajax())
{
$data = Input::get('ajaxdata');
return View::make('forms.contact')->with('data', $data);
}
I hope this helps you... This controller method just calls a view, but you can use the same method to access any controller function you might need.
This method returns no errors, and is generally much less risky than putting JS in your views, which are really meant more for page layouts and not any heavy scripting / calculation.
public function getWebServices() {
$content = View::make("_javascript.webService", $data);
return (new Response($content, 200))->header('Content-Type', "text/javascript");
}
return the above in a method of your controller
and write your javascript code in your webService view inside _javascript folder.
Instead of loading get datas via ajax, I create js blade with that specific data and base64_encode it, then in my js code, I decode and use it.

How to Use Relative URL in Ajax Post in MVC3

I have an Ajax post call written in a separate ".js" file which I call in multiple pages.
My code looks like this:
$.ajax({
url: '/MyVirtualDirectory/Controller/Action',
type: 'POST',
dataType: 'json',
....
....
})
Each time I change my virtual directory in my server, I'm required to change the code in "URL" to make my Ajax call working.
Is there any method that can make my code independent of my "Virtual Directory" name in IIS ..?
My application is MVC3.
Description
You should use the Url.Action method. But in your case, a seperate js file, you cant access this method. So i would create a javascript variable for each url in your view. Then you can use this variable in your js file.
UrlHelper.Action Method - Generates a fully qualified URL to an action method.
Sample
Your View
<script type="text/javascript">
var myUrl = '#Url.Action("actionName", "controllerName")';
</script>
<script type="text/javascript" src="yourJsFile.js"/>
Your js file
$.ajax({
url: myUrl,
....
})
Update
Another way is to store your url in a hidden field inside your view and get the hidden fields value inside your js file.
More Information
MSDN - UrlHelper.Action Method
I finally found a partial work around.
In my .js file i did some dirty coding like this:
var Path = location.host;
var VirtualDirectory;
if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
VirtualDirectory = "";
}
else {
var pathname = window.location.pathname;
var VirtualDir = pathname.split('/');
VirtualDirectory = VirtualDir[1];
VirtualDirectory = '/' + VirtualDirectory;
}
$.ajax({
url: VirtualDirectory/Controller/Action,
....})
The basic idea is I check the URL for localhost and port number. If both are there, it means that then I'm debugging in my local machine and so I don't need virtualdirectory in URL. If I'm running a hosted version then there won't be localhost and port number in my URL(provided I'm hosting on port 80).
And by this way when I run on my local machine while debugging the url will be only Controller/Action and while I host the URL will be VirtualDirectory/Action/Controller. It works fine for me now.
But please post if there is any other simple method.
I think it would be safer to declare a global Javascript variable and then set the variable for the first time, maybe when Home/Index fires. and then reuse it in every ajax calls like so:
$.ajax({... url: GlobalVariablePath + "Controller/Action/RouteValues" ...})
if you already designed your WebApp and every thing works fine and stuck when site is deployed, then you can manipulate the all ajax URLs like so:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
settings.url = GlobalVariablePath + settings.url;
}
});
Using this way, you can safely use the existing js codes and leave the rest without change.

Relative URL inside $ajax with asp.net mvc 3

I know one can use this function
#Url.Action("MyInfo", "Home")
to avoid the hardcoding of urls, but my $.ajax calls are in a separate .js file. Would the above still work?
From my knowledge, the #Url.Action will only work inside the Razor file. But considering that we are advised to use non-obtrusive JS, I am not quite sure how I would use the #Url.Action.
Please advise.
Would the above still work?
No.
From my knowledge, the #Url.Action will only work inside the Razor file
Your knowledge is correct.
But considering that we are advised to use non-obtrusive JS, I am not
quite sure how I would use the #Url.Action.
You could use HTML5 data-* attributes on some DOM element that you are unobtrusively enhancing (unless this element is already a <form> or an anchor in which case it already contains an url):
<div id="foo" data-url="#Url.Action("foo")">Hello</div>
and then in your separate javascript file:
$(function() {
$('#foo').click(function() {
var url = $(this).data('url');
// TODO: do something with the url
});
});
Add a function parameter for the relative paths. E.g., in your View:
<script type="text/javascript">
var path = "#Url.Action("ActionName", "ControllerName")";
someAjaxMethod(path)
</script>
and in your external js file:
function someAjaxMethod(path)
{
var data = {};
$.ajax(path, data)
}

Resources