jQuery: determine the [server's] Document Root

Omar picture Omar · May 30, 2014 · Viewed 20.7k times · Source

in PHP you can get the document root by: $_SERVER['DOCUMENT_ROOT']. Ej:

PHP

<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/example/directory/';
$file = 'some-file.html';

include( $root . $path . $file );

...etc
?>

How can I get the value of $_SERVER['DOCUMENT_ROOT'] in jQuery/JavaScript?

jQuery

//Example:
var root = ????;
var path = 'example/directory/';
var file = 'some-file.txt';

$("#example").load( root + path + file );

Notes: Whenever I work on directories, on an HTML page, the "BASE" directory becomes the directory of the current file. Ej, www.ejample.com/documents/examples/this-ex.html. If I just call $("#example").load( path + file ) the request would be documents/examples/ + example/directory. Like I said, it's not a question about server-side stuff. Is about getting a correct (and automatic) directory position

Answer

Tom Studee picture Tom Studee · May 30, 2014

Are you looking for document.location.hostname?

var root = document.location.hostname;

$("#example").load( root + path + file );