Search code examples
jqueryasp.net-mvcasp.net-mvc-4postwindows-server-2012

My jQuery post URL works fine in the IDE, should it be changed out in production on the server?


I am using jQuery post to make a post request to the server and it works fine in the IDE, but out on the production server it fails silently.

The URL I post to is this: $.post("/NffCall/GetNffOrdersCallInfo", ... );

I makes a post request to this action method: [HttpPost] public JsonResult GetNffOrdersCallInfo()

My IDE URL looks like this:

http://localhost:54415/NffCall/Details/SE/10356392

My server production URL look like this:

http://appsrv-se.MyDomainName.dk/TCWebToolsTestTwo/NffCall/Details/SE/10356392

In the server production URL above, the URL paths are serverName.MyDomainName.dk/WebSiteName

The URL I am posting to in the IDE works fine: /NffCall/GetNffOrdersCallInfo

But I am wondering, should I change this URL to work out in the server production environment?

In the IDE I use [HttpPost] public JsonResult GetNffOrdersCallInfo() to dynamically generate some HTML with jQuery. When I run it out on the server. Just nothing is happening.

Am I missing some part in my URL, which is necessary in my scenario out on the server? Or what could be the problem? The server I am using is Windows Server 2012.


Solution

  • You seem to have hardcoded the url to your controller action in the javascript file instead of using an URL helper to generate it:

    $.post("/NffCall/GetNffOrdersCallInfo", ... );
    

    In an ASP.NET MVC application you should always use URL helpers to generate the url to a controller action. For example:

    <script type="text/javascript">
        var myUrl = '@Url.Action("GetNffOrdersCallInfo", "NffCall")';
    </script>
    

    and then you could use this global javascript variable:

    $.post(myUrl, ... );
    

    Alternatively to using a global javascript variable to store the url you could store it as part of the DOM. For example you are probably AJAXifying some HTML element such as a div, form, a button or whatever. So you could embed this url as part of the DOM element:

    <div id="someDiv" data-url="@Url.Action("GetNffOrdersCallInfo", "NffCall")">Click me</div>
    

    and then in your javascript file you might be subscribing to some click event or something on this element:

    $('#myDiv').click(function() {
        var url = $(this).data('url');
        $.post(myUrl, ... );
    });
    

    Notice how the url in all cases is generated by an URL helper respecting the routes you have defined and taking into account the hosting environment such as virtual directory names, ... So basically it is guaranteed that a correct url will be generated no matter where your application is run (locally, test, production, ...)