Question

In Visual Studio, I have some Javascript code on a site I'm developing. While I'm debugging I'm using the $ajax call to "localhost". When deployed, it will need to be the actual server:

$('#textInput_UserName').focusout(function () {
    var _username = $('#textInput_UserName').val();
    $.ajax({
        url: 'http://localhost:8809/Account/UserNameExists/',
        data: { username: _username },
        dataType: 'html',
});

When I publish, I need to transform that localhost to the actual domain:

$('#textInput_UserName').focusout(function () {
    var _username = $('#textInput_UserName').val();
    $.ajax({
        url: 'http://www.mydomain.com/Account/UserNameExists/',
        data: { username: _username },
        dataType: 'html',
});

Is there an easy/automatic way to do this, similar to the way Web Config transforms work?

Many thanks!

Was it helpful?

Solution

You don't, you just omit the host, the browser will fill this in for you, like this:

$('#textInput_UserName').focusout(function () {
    var _username = $('#textInput_UserName').val();
    $.ajax({
        url: '/Account/UserNameExists/',
        data: { username: _username },
        dataType: 'html',
});

If you're actually talking about x-domain requests, which I doubt you are, then just set a global js site variable.

OTHER TIPS

I recommend you to use this:

url: '<%= ResolveClientUrl("~/Account/UserNameExists/")',

If you do it this way you'll avoid problems if you:

  • install the app in a virtual directory instead of the domain root
  • move your page to a different directory level in your app
  • use your service from a master page or user control, which can be instantiated in different pages, an thus directory levels

You can also expose a public property in your page/user control/master page, and use it from code in the same way, i.e:

  • code in the page/uc/master: public string ServiceUrl { get { return ResolveClientUrl("~/Account/UserNameExists/");}
  • code in .aspx: url: '<%= ServiceUrl',

Are you making a call to a web service or what is the destination of this url? When I am working with ajax calls in my web applications I usually set up the methods inside of a web service and call them like this:

 $.ajax({
        type: "POST",
        url: "../Services/BookingService.asmx/GetVerifiedReservations",
        data: paramsJson,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (response) {
            invalidDays = $.parseJSON(response.d);
        },
        error: function (xhr, textStatus, thrownError) {
            alert(textStatus);
            alert(thrownError);
        }
    });

As you can see the path is relative to the rest of the files in your domain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top