Javascript paths relative to file

20,248

Unfortunately this is not easily possible.

However, you could try finding the <script> tag in the HTML document and parse its location. Together with location.href you can then build an absolute URL to the script.


However, since you are calling PHP scripts - which clearly do not belong into the JS folder - your problem shouldn't be an issue at all. Your AJAX calls will be relative to the document containing the scripts and you probably know the path to your PHP scripts from that document.

Update: Just read that files from different folders are using those scripts. In this case the script tag parsing technique is actually the way to go if you don't want to simply set a var containing the path manually.

Share:
20,248
RANGER
Author by

RANGER

CEO and Co-Founder of Directus.

Updated on July 09, 2022

Comments

  • RANGER
    RANGER almost 2 years

    I have written a web app where the JS file lots of relative calls to other files. This has worked up to this point but now I am using this js file from pages in different directories and I am getting errors with the paths. This web app will be installed on lots of different hosts so I don't know if absolute paths will work as I won't know where it is installed. I also don't want to junk up the js with lots of prepended variables in my paths (but might have to).

    I would LIKE the js paths to be relative to the js file itself and not the document opening it... is there a way to set a default root directory within a js file?

    $.ajax({
        type: "POST",
        url: "inc/alert.php",
        success: function(msg){
            if(msg){
                window.location.href = 'inc/logoff.php?timeout=true';
             }
        }
    });
    

    This is my file structure, but I don't know where it will be installed or what the webapp folder will be called:

    /random-folder/web-app/inc/script.js

    And until now all my files using the js were in the "web-app" folder... but now I have other pages calling it in different folders and all of the paths are broken. Is there a way to do this? Or is there at least a way to get the path of the js file itself?

    Thanks in advance for any help...