Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the root path in JavaScript?

I am using mod_rewrite to remap the URLs in my website in the following format:

http://www.mydomain.com/health/54856

http://www.mydomain.com/economy/strategy/911025/

http://www.mydomain.com/tags/obama/new

The problem is that I am making AJAX calls to a file: http://www.mydomain.com/login.php

And I don't want to write the FULL url or even use the ../ trick because there isn't a fixed level of folders.

So, what i want is something to access the login.php from the root, whatever the domain name is:

 $.ajax({
    type: "POST",
    url: "http://www.mydomain.com/login.php"
 });
like image 699
CodeOverload Avatar asked Mar 17 '10 21:03

CodeOverload


2 Answers

What about:

$.ajax({
    type: "POST",
    url: "/login.php"
});

Make sure that you allow access to /login.php from your mod_rewrite rules.

like image 163
Daniel Vassallo Avatar answered Oct 02 '22 17:10

Daniel Vassallo


You could also define a variable for JS to use in your HTML head:

<script type="text/javascript">
// siteRoot will be equal to http://www.yourdomain.com/
var siteRoot = '<?php echo $theSiteRoot; ?>';
<script>

And then append the siteRoot variable in your AJAX calls.

$.ajax({
    type: "POST",
    url: siteRoot+"login.php"
});

Just make sure to print the siteRoot variable before including your .js files.

Another way to get this working is using the HTML base tag. All the client-side requests will be made on that target. Include it before any link/script declaration.

<base href="<?php echo $theSiteRoot; ?>" />

Hope this helps :)

Edit:

Your wont need to append anything to your AJAX calls if you make use of the base tag method. Just a plain call will do the trick.

$.ajax({
    type: "POST",
    url: "login.php"
});
like image 23
Mariano Cavallo Avatar answered Oct 02 '22 15:10

Mariano Cavallo