laravel how to route to a route on a javascript?
Asked Answered
P

4

9

I have this jquery

$(".waitingTime .button").click(function () {
    alert("Ema");
});

I have a a tag like this:

<a href="{{ URL::to('restaurants/20') }}"></a>

Can I do the same href action in the jquery function?

Many Thanks

Personable answered 22/6, 2014 at 17:22 Comment(2)
What do you mean same href action?Glossolalia
@RahilWazir I mean like when I click on a tag, the browser goes to the href url. I would like to have the same feature in a javascript function. but here it is laravel, maybe it is different? I don't knowPersonable
K
26

yes this is possible and has nothing to do with Laravel. There are different possibilities. If your query is embedded within the same laravel view, you put the URL directly in your jQuery code, for example like this:

$(".waitingTime .button").click(function () {
  window.location.href = "{{URL::to('restaurants/20')}}"
});

But I think the best option is to add the URL on your button tag as a data attribute and then let jquery go to that URL. That way you can make your buttons more dynamic and have more capsulated code.

One example might be:

<div class="waitingTime">
  <button class="button link-button" data-href="{{URL::to('restaurants/20')}}">
  Click me
  </button>
</div>

$(".link-button").click(function () {
  window.location.href = $(this).data('href');
});

That way you can always give a button with the class link-button a data-href attribute with the URL you want to open when the button is clicked and don't have to add additional jquery.

Kenwood answered 22/6, 2014 at 17:50 Comment(0)
A
2

Just output php in your javascript

$(".waitingTime .button").click(function () {
    window.location.href = "<?php echo URL::to('restaurants/20'); ?>";
});
Anderaanderea answered 22/6, 2014 at 17:46 Comment(2)
You should use laravel's synthax: {{}}. It applies some cool stuff.Nebulosity
Personally, I'm not a fan of this answer, php in javascript, it's rather averageGuidotti
S
0

if need variable from js can use this

if(data.cookies == 0){
                  location.replace("{{ route('delivery') }}?id="+id);
                    }
Sensualism answered 17/12, 2020 at 23:38 Comment(0)
H
0

In Laravel we can decide how to route in Jquery by URL parts:

var url = $(location).attr('href');
parts = url.split("/");
id= parts[parts.length-1];
name= parts[parts.length-2];

if(id == 'xxxx') {
  window.location.href = "{{ route('route_name') }}?id="+id+"&name="+name;
}else{
    //do something
};
Homozygous answered 30/5 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.