JavaScript relative path of AJAX call
I have a script containing PHP and JavaScript files. All of these files are located in the root folder /myfolder
.
Let's say a script that is supposed to include on my site /myfolder/script.js
, the problem is that in script.js
I have ajax calls to ../myfolder/ajax.php
which, since the path will be relative to the page, the script will not be included if I had something like this on the page /a/b/page.php
:
<script src="../../myfolder/script.js><script>
because this will call the ajax method from ../myfolder/ajax.php
as specified in the AJAX call, which in this case is /a/myfolder/ajax.php
.
How can I rewrite the AJAX call url so that it always points to the right file, no matter where it is included script.js
?
ROOT
|---myfolder
|--script.js
|--ajax.php
|--page1.php
|--subfolder
|--page2.php
|--subfolder
|--page3.php
source to share
/**
* returns the current context path,
* ex: http://localhost:8080/MyApp/Controller returns /MyApp/
* ex: http://localhost:8080/MyApp returns /MyApp/
* ex: https://www.example.co.za/ returns /
*/
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
at a url like http://www.example.com/ajax
:
getContextPath() + 'myfolder/ajax.php'
will return /ajax/myfolder/ajax.php
similarly for the url, for example http://www.example.com/
:
getContextPath() + 'myfolder/ajax.php'
will return /myfolder/ajax.php
Finally, to a url like http://www.example.com/myfolder/a/b/c/d/e/f/g/
:
getContextPath() + 'myfolder/ajax.php'
will return /myfolder/ajax.php
source to share