Praveen Srinivasan
Praveen Srinivasan

Reputation: 1620

Get base_url using Jquery in Laravel

I am using laravel 5.0. I want to get base url of laravel page using jquery. I have tried the following function.

function getBaseURL () {
   return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
}

But this gives only http://localhost. I need my full base url in jquery. What to do?

Upvotes: 6

Views: 41562

Answers (3)

Shah-Kodes
Shah-Kodes

Reputation: 163

The solution is easy , All you need to just use below code :-

var appBaseUrl = {''};

This variable will return something like http://yourexampledomain.com

Furthermore if you want to add your controllers and action to this url i.e. for Ajax call , then that will be simple too :-

var finalUrl = appBaseUrl+'/controller/action';

Result is :- http://yourexampledomain.com/controller/action

Now use finalUrl in your calling route for ajax calls.

Upvotes: -3

Björn
Björn

Reputation: 5876

Do you mean you want the base url of your laravel app available anywhere your javascript?

You can include this in your template.blade.php:

<script type="text/javascript">
var APP_URL = {!! json_encode(url('/')) !!}
</script>

And than access that var anywhere in your javascript:

console.log(APP_URL);

Upvotes: 49

Suganya Rajasekar
Suganya Rajasekar

Reputation: 684

You can also use this:

<script type="text/javascript">
      var base_url = '{!! url() !!}';
</script>

You can call it any where in js files like "base_url"

It return upto your public path without slash at end

Ex: www.example.com

If you need to add slash at end you can use this..

<script type="text/javascript">
      var base_url = '{!! url().'/' !!}';
</script>

It return upto your public path with slash at end

Ex: www.example.com/

Upvotes: 8

Related Questions