View Full Version : Properly formatting URL with javascript to locate php file

12-09-2011, 05:42 AM
This has been driving me nuts, let me start off by saying this is what I'm currently working with...

I've included a js file in the header of the site which utilizes a function in a php file. Just the standard
<script language="javascript" src="http://yourwebsitehere.com/includes/js.js"></script>

In the .js file I'm setting the location to a php file as a variable...

var url="/file-here.php";

Obviously the document.location.host isn't working for me but here's what's going on...

At first I just had,
var ="http://www.domain.com/file-here.php"; in the js file.

So if the user is on www.domain.com/some-directory/another/ the script will work, however if the user is on domain.com/some-directory/another the script won't work, because I've included www. in the variable within the js file.

However, if I set it to
var ="http://domain.com/file-here.php";, it will work on domain.com/some-directory/ but not on www.domain.com/some-directory.

So basically I need to return the host url somehow, depending on if the user is on the page with www. or without www. so it will always work.

With php, I could just use
$server['HTTP_HOST']/file-here.php and it will always return www.domain.com or domain.com depending on the URL the user is on, but obviously php won't work in a js file so I'm looking for the correct string/command to get this.

Anyone have any idea how to return just the www.domain.com or domain.com portion of the current URL with javascript?

So no matter where they are on the site, with or without www. the script can still function by having the correct URL to the PHP file at all times?

12-09-2011, 07:45 AM
well, the location is a property of the window Global object, not of the document object. Thus the reference should be:

or (as window can be eluded, as being the Global Object in JavaScript):

12-09-2011, 03:06 PM
Thanks for the reply that's what I was looking for.

I found
location.host does exactly what I need, however for some reason although the URL variable becomes the proper format when using it, the script doesn't function properly. I'm not entirely sure why.

Oh well, that makes it a different situation but at least I know how to write out the domain.com or www.domain.com with
location.host now :thumbsup: