Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel how to route to a route on a javascript?

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

like image 956
Anastasie Laurent Avatar asked Jun 22 '14 17:06

Anastasie Laurent


People also ask

What is the difference between URL and route in Laravel?

For a start it is using a named route. This means that the link between the form and its controller are not dictated by the url that the user sees. The next advantage is that you can pass additional parameters into the route helper and it will put those in the correct place in the form action.

What is reverse routing in Laravel?

Laravel reverse routing is generating URL's based on route declarations. Reverse routing makes your application so much more flexible. For example the below route declaration tells Laravel to execute the action “login” in the users controller when the request's URI is 'login'.


2 Answers

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.

like image 70
Matthias S Avatar answered Oct 10 '22 07:10

Matthias S


Just output php in your javascript

$(".waitingTime .button").click(function () {
    window.location.href = "<?php echo URL::to('restaurants/20'); ?>";
});
like image 30
Krimson Avatar answered Oct 10 '22 07:10

Krimson