Search code examples
javascriptrelative-pathinclude-path

JavaScript relative AJAX call path


I have a script containing PHP and JavaScript files. All these files are in the root folder /myfolder.

Let's say the script I have to include on my website is /myfolder/script.js , the problem is that in script.js I have ajax calls to ../myfolder/ajax.php, which, because the path will be relative to the page the script is included won't work 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 stated in the AJAX call, which in this case is /a/myfolder/ajax.php.

How can I rewrite the AJAX call URL so that it will always point to the right file regardless where the script.js is included?

ROOT
|---myfolder
    |--script.js
    |--ajax.php
|--page1.php
|--subfolder
   |--page2.php
   |--subfolder
      |--page3.php

Solution

  • /**
     * 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) ? '' : '/');
    }
    

    on a URL like http://www.example.com/ajax:

    getContextPath() + 'myfolder/ajax.php'
    

    will return /ajax/myfolder/ajax.php


    similarly on a URL like http://www.example.com/:

    getContextPath() + 'myfolder/ajax.php'
    

    will return /myfolder/ajax.php


    lastly on a URL like http://www.example.com/myfolder/a/b/c/d/e/f/g/:

    getContextPath() + 'myfolder/ajax.php'
    

    will return /myfolder/ajax.php