Relative Path Problems in Javascript Ajax call

Pointy's way works, but you have to know in advance where you're going to deploy it.

Alternately, simply don't start the relative path with a /:

var url = "Shared/AskReason.ashx?REASON=" + reason;

That will be resolved relative to the current document's location. So if the current document is:

http://localhost/myapp/index.aspx

...then that will resolve to

http://localhost/myapp/Shared/AskReason.ashx?REASON=foo

Paths that start with a "/" (and no protocol & host) are relative to the root of the host. If you deploy such that your application is at "http://whatever/myapp", then your root-relative paths have to start with "/myapp".

When you're working in a server-side environment that involves some sort of page template mechanism, a common trick is to have that part of the path be some kind of configuration variable so that you can write pages with paths like:

<a href='${root}/something/something'>click me</a>

Then that "root" variable is expanded based on configuration to "/myapp" or whatever.


I had a similar problem where an absolute URL was needed but the reference broke when going from localhost to the production server. I resolved it by checking if a "localhost" string exists in:

var environ = window.location.host;

Then you can simply do:

if (environ === "localhost") {
    var baseurl = window.location.protocol + "//" + window.location.host + "/" + "shared/";
} else {
    var baseurl = window.location.protocol + "//" + window.location.host + "/";
}

Then you can add baseurl in front of whatever url you need to reference.