Relative Path Problems in Javascript Ajax call

MDV2000 picture MDV2000 · Feb 23, 2011 · Viewed 65.2k times · Source

Okay, I have a JavaScript file with the following functions:

function AskReason() {
    var answer = prompt("Please enter a reason for this action:", "");
    if (answer != null)
        DoReason(answer);
}

function createXMLHttpRequest() {
    try {
        return new XMLHttpRequest();
    }
    catch (e)
    { alert('XMLHttpRequest not working'); }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    { alert('Msxml2.XMLHTT not working'); }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    { alert('Microsoft.XMLHTTP not working'); }
    alert("XMLHttpRequest not supported");
    return null;
}

function DoReason(reason) {
    var xmlHttpReq = createXMLHttpRequest();
    var url = "/Shared/AskReason.ashx?REASON=" + reason;
    xmlHttpReq.open("GET", url, true);
    xmlHttpReq.send(null);
}

This line:

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

Is what is causing the problem.

In VS 2010 debugging the app - this call works to my ashx handler.

When I move the project to a virtual directory - example http://localhost/myapp

this code will break and I have to change the javascript to this:

var url = "http://localhost/myapp/Shared/AskReason.ashx?REASON=" + reason;

Any ideas on how I can fix this to work in both environments or just accept the manual change when I deploy apps to servers?

Thanks, Mike

Answer

T.J. Crowder picture T.J. Crowder · Feb 23, 2011

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