Luke
Luke

Reputation: 5076

Make javascript use the directory it's in

I have a small script called foo.js in a folder called test where the location of the directory is unknown:

$.post("bar.php");

It's used by two different html files, one at /test/index.html:

<script src="foo.js"></script>

The other at /test/index.html:

<script src="../foo.js"></script>

When I run the script from /index.html, it works fine and bar.php is called. But when I call it from /subdirectory/index.html, javascript tells me that the resource (bar.php) can't be found. However if I copy and paste bar.php into /subdirectory, it works.

Is there a way to have javascript use the directory the script is located at (in this case, test), instead of using whatever directory it was originally called from?

Upvotes: 2

Views: 152

Answers (2)

Paul
Paul

Reputation: 141839

Use a path relative to your domain, by starting it with /:

$.post("/bar.php");

This way it doesn't matter where the script is, or where the HTML file that called it is, only the location of bar.php matters. You should also probably include foo.js the same way:

<script src="/foo.js"></script>

That will work in both files /index.html and /subdirectory/index.html.

Edit: To actually find out where your script is located, relative to the current page, you can use this:

(function(){
  var myDirectory = (function(){
    var script = document.currentScript || // SHIM
      (function(){
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length - 1];
      })();

    var src = script.getAttribute('src');
    return src.substr(0, src.lastIndexOf('/')) + '/';
  })();


  // The rest of your script here, then, wherever you make the post request:
       $.post(myDirectory + "bar.php");

})();

Upvotes: 5

Matt Urtnowski
Matt Urtnowski

Reputation: 2566

Try /bar.php

You need to use relative paths

Upvotes: 2

Related Questions