How to use the function url() in a js file Hello,
I would like to use the function url() in a javascript file, because I don't want to write in hard the URL.
I tried something like that but it doesn't work :
url = <?php url('file/file2') ?>
Somebody has a solution ?
url = <?php echo url('file/file2') ?>
Also, you might need quotes around it if its JS:
var url = "<?php echo url('file/file2'); ?>";
:D
// note the quotes
url = '<?php echo url('file/file2') ?>'
// or maybe even
url = '{!! url('file/file2') !!}'
All the solutions doesn't work :(
//Doesn't work, if I do an alert, I have nothing
url = '<?php echo url('file/file2') ?>';
url = '{!! url('file/file2') !!}';
//Doesn't work, if I do an alert, write this : .../public/<?php echo url('file/file2'); ?>
var url = "<?php echo url('file/file2'); ?>";
You need to do this within <script> tags in your layout view. Are you trying to load this through an external js file?
<script>
var url = "<?php echo url('file/file2'); ?>";
</script>
@pimous
All the solutions doesn't work :(
It doesnt work in a js file as they are not parsed.
You have to put this in a blade template between script tags. Because the blade template is parsed so php is interpreted.
The strategy is to declare all your variables in the blade file then pass them to a js function defined in your js file.
@pimous All example will not work !
In *.js file you are unable to use php or blade tag
it is a subject that dates a long time ago but I still come with my element of response
in your view blade header you can do it
<divtype="hidden" id="path" value="url('/')">
and in all your js or jquery file , you make
var path = $("#path").val();
and when you want to put url , just do
example : href="'+path+'/nameofroute"
Please sign in or create an account to participate in this conversation.