Relative URL in JQuery Post Call

jquery ajax relative url
jquery ajax url relative path
call controller method from jquery ajax
xmlhttprequest relative url
mvc jquery post'', url action
$.post jquery
url action with parameter in ajax call
how to set url in ajax call

I have the following situation.

I developed my first MVC Asp.Net application. it runs on my server at the following adress

http://localhost:59441/

I wrote some JQuery Post Methods that looked like this

  $.ajax({
        type: "POST",
        url: "/CeduleGlobale/UpdateCheckBox", ...

CeduleGlobale is my ControllerName and UpdateCheckBox is my methodName

When I put the Application on the testServer, it was put in a VirtualDirectory

hence the application is now

http://testServer/JprApplication/

no more port to specify and also an application Name

When I started to test, I quickly noticed my JQuery Post calls didn't work anymore...

I modified them so now the URL is

/JprMvc/CeduleGlobale/UpdateCheckBox

the problem is 2 fold.

  1. this makes it hard to test on my development machine because IIS Express doesn't allow me to specify a virtual Directory.
  2. I don't like hardCoding the Virtual Directory Name in the JQuery because I dont know what name the Application will have in the production environment and therefore i will have to modify my script before i can install the application in production.

I am sure I am missing some basic thing to simplify this.

Thanks

Depending on where you actually have your JavaScript located (inside the View or a separate JS file), you have a couple of options.

Option 1 - Inside the View

Simply use the Html Helpers to generate the links for you

<script type="text/javascript">
   $(function(){
        $.ajax({
           type: "POST",
           url: "@Url.Action("UpdateCheckBox", "CeduleGlobale")"
        });
   });
</script>

Option 2 - Standalone JS File

We typically have a function per page that sets up that page's handlers. So, we can do something like the following:

View

<script type="text/javascript">
    $(function(){
        SetOrderPage('@Url.Action("UpdateCheckBox", "CeduleGlobale")');
    });
</script>

Standalone JS File

function SetOrderPage(ajaxPostUrl){
       $.ajax({
           type: "POST",
           url: ajaxPostUrl
       )};
}

Option 3 - Standalone JS file Method 2

You could have a global variable in your in your JS file that is the siteroot. The draw back here is that you will need to hand create each of your action method paths. On each page, you could set the site root global variable as such:

Standalone JS File

var siteRoot;

View

<script type="text/javascript">
    siteRoot = '@Request.ApplicationPath';
</script>

Keep in mind you cannot use Razor syntax in a stand alone JS file. I believe that it is best to let Razor/MVC/.NET dynamically give you the site path or URL route as it will really cut down on the mistakes that could be made when moving between sites/virtual directories.

Generate Reliable URLs in ASP.NET MVC AJAX Calls -- Visual , But the truth is that, once you move out of testing in Visual Studio, these relative URLs aren't reliable. What worked in test won't work when you  Stack Overflow Public questions and How to Use Relative URL in Ajax Post in MVC3. I have an Ajax post call written in a separate ".js" file which I call in

As far as I know there is no other way around this. Unless you are willing to user relative URL's i.e:

$.ajax({
        type: "POST",
        url: "./CeduleGlobale/UpdateCheckBox", ...

But that can get messy for various reasons when you refactor code. Alternatively prepend the URL which is globally defined and therefore you then only need to change it in once place before going to production.

i.e.

//Globally defined serverRoot
serverRoot = "http://someaddress/somevirtualdirectory";

$.ajax({
        type: "POST",
        url: serverRoot + "/CeduleGlobale/UpdateCheckBox", ...

That way if you don't need it you can just set serverRoot = ''; and all will be back to how it is now.

How to give Relative path in javascript external file?, Hi All, I have an External JavaScript file It Contains Ajax Call like Then you could set this static URL as the value of jquery ajax url option. The scenario is that when the service will be deployed on server, it will have a different URL. What I want is that to pass relative URL in my JQuery so that I do not have to change it in future. Please note that my client application is different, i.e my JQuery is in another website.

I had this kind issue on MVC 5 using JQuery, so I went to this solution that gets rid of the problem when you are in Localhost, and in any Navigator even when you're deploying app in a subfolder.

var pathname = window.location.pathname;
var VirtualDirectory;
if (pathname.indexOf("localhost") >= 0 && pathname.indexOf(":") >= 0) {
    VirtualDirectory = "";
}
else {
    if ((pathname.lastIndexOf('/')) === pathname.length + 1) {
        VirtualDirectory = pathname.substring(pathname.indexOf('/'), pathname.lastIndexOf('/'));
    } else {
        VirtualDirectory = pathname;
    }
}

And then in any ajax call :

$.post(VirtualDirectory + "/Controller/Action", { data: data}, "html")
             .done(function (result) {
                 //some code             
});

ajax url path, Relative URL in JQuery Post Call. In the url path, when I give the Controller/​Action path it … jQuery Color SVG Color Names 2.1.2 - uncompressed, minified. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

I know this is an old post. But, I had the same issue and ended up here. And managed to fix that issue with UrlHelper.Action method. It should be used something like this. (Note that this specific solution will works within the view.)

url: "@Url.Action("UpdateCheckBox", "CeduleGlobale")",

Hope this helps. :)

ajax url path, jQuery Color With Names (last two together) 2.1.2 - uncompressed, minified. I have problem with the ajax post url it keep go to difference url path i have a few base]) Parameters url A USVString representing an absolute or relative URL. I am trying to put comments on Facebook wall using jquery. But my ajax call not alowing external url . can anyone explain how can we use external url with jquery ? below is my code : var fbUrl=

Pass @Url.Action("action","controller") to the javascript from the view. This will allow it to be update dynamically at run time.

<script>
   myJavascriptfunction(@Url.Action("action","controller"),param1,param2);
</script>

There may be a function to get the root path also which you could use to initialize the root variables in the previous answers.

How to redirect to a relative URL in JavaScript?, How to create UI Datepicker using jQuery ? How to convert jQuery to JavaScript ? ASP.NET Core is a modern web development framework by Microsoft. You can build any type of projects – big or small, in this framework. ASP.NET Core is based on Model View Controller (MVC) architecture where any HTTP based request is captured by a Controller which then passes the response to the View.

Convert relative path URL to absolute path URL using JavaScript , Convert relative path URL to. absolute path URL using JavaScript. </ title >. < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" >. Relative URL in jQuery POST Call Asp.Net MVC 5 One of the major problem encountered in my website were, all ajax call placed in sepa Relative URL in jQuery POST Call Asp.Net MVC 5

ajax url path, Ajax call does not hit the url path in controller/action. The parameters specifies one or more name/value pairs for the AJAX … Relative URL in JQuery Post Call. The xml file i was trying to read was located in the same directory, so following standard rules it made sense for the url of the ajax call to simply be url: ‘myfile.xml’ however, this did not work.

ajax url path, jQuery Color SVG Color Names 2.1.2 - uncompressed, minified. If url is an Relative URL in JQuery Post Call. Ajax. If not specified, it defaults to ''. MVC5. $.ajax({ url : "/app-url/relative-url", type : "GET" }); Using $.ajaxPrefilter() to filter Ajax Requests. If you have been in server side web-development then you will acknowledge that filters are a great way to achieve certain objectives such as input values sanitation etc. Now jQuery provides this functionality in client side as well using

Comments
  • I'm personally not a fan of using route names unless they're really complicated, most of the time I just care about a simple controller/action so I use Url.Action("MyAction", "MyController") instead.
  • Thanks, but regarding Option 3: Pretty sure you don't want to use Server.MapPath as that exposes the physical directory mapped to that virtual path. You probably meant to use Request.ApplicationPath which is what is typically used to generate an "approot" string at runtime for use by JS methods (especially for COTS products, where app name cannot be hardcoded).
  • Option 3 - Instead of writing @Request.ApplicationPath to every single View, just write it once to your _Layout.cshtml (or whatever "master" page). Now you have a global variable available to all your JS files.
  • First part does not work.. Second part seems to work. thanks
  • Yes the first option is only going to work if the page which is calling it is relative to the server root. Relative url's are a headache at best and thus I would only really recommend my second suggestion above for many reasons!
  • Instead of "./CeduleGlobale... you might need window.location.pathname + "/CeduleGlobale... if you're using extensionless urls
  • Essentially this is the preferred solution (second part), but -1 for hardcoding the serverRoot path, and also for hardcoding the protocol (http). Recommend to instead use Request.ApplicationPath and emit that variable to JS. Then when you modify your protocol, host, and application name, you don't have to change every damn file that defines serverRoot