JQuery ajax .load() to reference to the correct url - javascript

I have a localhost with a few projects, so this project in VS2010 properties->web->use local IIS web server = 'localhost/project4/'. (I can't use the normal debug VS Development Server as some components won't work in my project) Anyhow, localhost is fine no big deal, so I go on coding.
Now, in ajax when I call .load('/Account/LogOn'); it gives me 'localhost/Account/LogOn' but what I really want is 'localhost/project4/Account/LogOn' because it is sitting in the project4 directory, not the root.
Any idea how to tell ajax I need that virtual directory prefix between domain name and the rest of the url?
EDIT --------------------------------------------
Thanks guys, combined with all your knowledge, I guess the best ways to do it are:
Include the js script into .cshtml server side and use "~/Account/LogOn/" let .net figure out the path.
Make a global var remove_me_debug_only_virtual_directory = "/project4/"; in js code. append it to the domain name. this way we don't have to pull .net into the water and write js code in .cshtml.
Move the project to localhost/ root if you can, in this case I can't, because other people at work wants to access this networked server and do demo.

If your JS code is in an MVC cshtml file, use it like this:
.load('#Url.Action("LogOn", "Account")');
The proper URL will be placed in the concrete JS code.

According to .net documents,
Absolute and relative path references in a server control have the following disadvantages:
Absolute paths are not portable between applications. If you move the application that the absolute path points to, the links will break.
Relative paths in the style of client elements can be difficult to maintain if you move resources or pages to different folders.
To overcome these disadvantages, ASP.NET includes the Web application root operator (~), which you can use when specifying a path in server controls. ASP.NET resolves the ~ operator to the root of the current application. You can use the ~ operator in conjunction with folders to specify a path that is based on the current root.
So as described above, using ~ will lead you to the root of your web project using asp:
<asp:image runat="server" id="Image1" ImageUrl="~/Images/SampleImage.jpg" />
For more information go to: Web Project Paths
Based on your update: Possible duplicate of: base url using jQuery
Where stated by #gregguida:
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
//all you need to do is work with l.pathname.split('/') to find what you need.

I am a java developer but the context is same in both case,
In your can follow the steps
Check the context of your server if root is "/" then you have to call something like,
.load('/project4/Account/LogOn');
If your application is root and you can calling this request from itself then
.load('Account/LogOn');

Related

Setting up a common route for javascript calls in ASP.NET MVC project

I have a bizarre routing issue with my ASP.NET MVC project that I hope you guys can help me with.
Overall everything works fine when I run the project off my localhost or run it on the server while it's deployed directly at http://myServerName. The problems start when I deploy the application to various enviornments on the server located under different virtual directories. For example: http://myServerName/QaEnviornment or http://myServerName/TestEnviornment
The problem is that all Javascript calls to application URLs ignore my environment virtual directories and fail.
For example on my QA server whenever I have to make an Ajax call I take a standard approach such as:
var myUrl = '/ControllerName/ActionMethodName/'
$.ajax({url:myUrl,success:function(){Do stuff} })
Because my application is deployed on http://myServerName/QaEnviornment, when rendered I expect myUrl to be http://myServerName/QaEnviornment/ControllerName/ActionMethodName. Instead it comes back as http://myServerName/ControllerName/ActionMethodName and ofcourse fails.
To get around this for now I declared a global Javascript variable that contains the environment folder name and when I build URLs for javascript calls I have to remember to ALWAYS construct them as var myUrl = myGlobalFolderVar + '/ControllerName/ActionMethodName/'
Using a global JavaScript variable to get around this issue seems as a bad solution to me. Is there anything I can do to get routing to work properly so whenever JavaScript calls are made whatever subfolder the application is running under is always included in the URL ?
Instead of always having to remember to construct them correctly, make a helper function that you call to create your URLs
function CreateUrl(string path){
return myGlobalFolderVar + path;
}
To answer your second question, not really. Routing is not aware of what made the request and you cannot always rely on the X-Http-RequestedWith header to base that decision on. In addition, your site application root is not at the domain root, therefore routing would only kick in when it visits your application. The only other way I am aware of is to have MVC actually generate the Url for you (var url = '#Url.RouteUrl(params)';) but this does not help at all when you have your JavaScript in a single or a few .js files.
EDIT
The above function is a JavaScript function that can sit anywhere you would like in your application, including external JS files. As for setting your myGlobalFolderVar, there are a few ways you could set this.
1.Actually hard code the variable in your external JS file.
var myGlobalFolderVar = 'TestEnviornment';
This is hard however if you are deploying to several different testing servers.
2.If you are using web.config transformations, you could add an AppSettings key/value pair in your web.config transformations depending on build type. Then, using that value, set your global Javascript variable in your master page layout/views.
<appSettings xdt:Transform="Replace">
<add key="folderLocation" value="TestEnvironment" />
</appSettings>
In your external JS file
//this makes it a site wide/global variable in any place you
//include your external JS file
var myGlobalFolderVar = '';
And in your master view
<script type="text/javascript">
myGlobalFolderVar = '#ConfigurationManager.AppSettings["folderLocation"]'
</script>
3.Same as number two, but use the URL helpers to figure out what the path to your application is in your master view instead of using the web.config transformations
<script type="text/javascript">
myGlobalFolderVar = '#Url.Content("~/")'
</script>
The basic idea is using .NET to figure out where it lives and set a global JavaScript variable with that path information. Then, in conjunction with the helper JavaScript function provided at the top of this answer, you can correctly generate paths as needed throughout your application - regardless of path depth, deployment location or any other deployment type concerns.
var myUrl = CreateUrl('/ControllerName/ActionMethodName/');
$.ajax({url:myUrl,success:function(){Do stuff} });

asp.net MVC routing - javascript url 404 errors

While developing my app (asp.net mvc3) locally everything was fine using the VS dev app server. The app was located at localhost/. However, I'm attempting to deploy the application on a IIS 7.5 server in a /Management directory and having a lot of routing issues as a few calls in my app rely on the app being at the route.
I have some javascript code that calls my controller through an ajax call that looks like this:
url: "/en/Home/GetFormula/"
I would like it to go to: /Management/en/Home/GetFormula but instead it's going to the root of the site and looking for /en/Home/GetFormula and returning 404 errors.
Any ideas on how I can fix my javascript routing to default /Management/ as the root of the site?
Thanks
When the pseudo-URL passed to an HTTP request begins with a slash (e.g. "/path/to/resource"), the pseudo-URL is "completed" by treating it as if the given path were under the Web site's root directory (e.g. "http://my.site/path/to/directory").
Clearly, you were expecting the pseudo-URL to be processed as if the given path were under your Web application's root directory. Well, I have bad news for you: The HTTP protocol does not deal with such a thing as a "Web application".
The ASP.NET MVC Framework provides the Url.Content function, which takes pseudo-URLs beginning with a tilde character (e.g., "~/path/to/resource") and returns the result of replacing the tilde character with the Web application's root directory (e.g., "http://my.site/an/application/path/to/resource", assuming the Web application's root directory is "http:/my.site/an/application"). However, the ASP.NET MVC Framework is only available on the server side. If your JavaScript runs on the client side, it cannot call Url.Content.
But not all is lost. The ASP.NET MVC Framework allows you to dynamically generate JavaScript code on the server and run it on the client, the same way it allows you to dynamically generate HTML content and of course send it to the client. That way, you can expand the pseudo-URLs into actual URLs on the server side, and deploy the resulting JavaScript code to the client.
To avoid confusion about where you are currently try:
url: document.URL + "/Management/Home/GetFormula"
I solved this issue adding a html hidden field on my page where, on the server side, I put the correct url inferred with the Url.RouteUrl method like this:
<input id="MyHiddenFieldName" name="MyHiddenFieldName" type="hidden" value="#Url.RouteUrl(new { area = "MyArea", controller = "MyController", action = "MyAction" />
then, on your javascript code you could do this:
url: $("#MyHiddenFieldName).val()

javascript get Path Name represented in "browser address bar"

Is there any way to get the requested path (the path displayed in the browser address bar) vs the redirected path for a subdomain (hidden from the user) using javascript
I am using a shared javascript file (shared across multiple pages and sites) that determines the controller and action (MVC) using window.location.pathname but... I have just caught myself out as my deployment runs under sub-domains which I wasn't representing in the Visual Studio dev environment. the sub-domains on my host redirect to a /subdomain folder as is usually the case but now my window.location.pathname pulls back /subdomain/controller/action whereas the URL in the address bar is /controller/action
Obviously I can tweak my javascript to handle this situation - however there may not always be a subdomain (at least in my dev environment if nothing else - and I am dead against solutions like having "isdev" style flags throughout my code) so I have to have a fail-over for those instances which means things start to get a little more complicated thus being more prone to error.
Any suggestions greatly appreciated.
Btw I do not want to use values from .Net e.g. HttpContext... as my js is in an external file and I do not want to create a dependency on data in a view for it to work as this means every time I consume the js on a new page I have to remember to include the additional logic in the view for it to work, plus if I change my js file it may result in me having to refactor a bunch of views as well.
Cheers
Rob
window.location.href should return the entire URL that the site is currently at, including the subdomain e.g. http://subdomain.site.com/path/to/page.aspx
Alternatively you can use window.location.host and it will return everything except for the path, or window.location.pathname to return just the relative path to the file.
See the MDC article on window.location for more information: https://developer.mozilla.org/en/DOM/window.location

JS Ajax: local vs absolute path issue when using SEO friendly urls

here's the thing:
i built my site with SEO friendly urls...but i have problem now calling ajax files becaus eth epath is wrong and I cant set an absolute url when i call my files in background..
for instance my page is here (similar to StackOverflow..)
www.domain.com/product/123/this-is-a-product
but my javascripts functions, in folder /js,now they try to reach the files but they cant obvisouly because are set to relative path...
how can i solve this issue??
EDIT: Found this How to get the root path in JavaScript?
When you are using freindly urls, then you have to use path started with /. But then you are starting path from main path.

url paths for resources

i am a newbie on web development, so i have some problems first of all what is the meaning of ~, / on an url? My real question in my javascript code i am doing some ajax calls with jquery like that
$.ajax({
...
url: '/Membership/Login',
...
});
There is an Membership controller with an Login action method that i need to send data to. When i publish this project to IIS (my application is under xxx folder of wwwroot) i get wrong url address.
I get :
http://localhost/Membership/Login
I expect : (because my application is in xxx folder)
http://localhost/xxx/Membership/Login
Note : I dont want to add xxx to all urls.
When you use ~ in a url and call the ResolveUrl method it will put in the path to your application. You can do this in your aspx page by going:
<%=ResolveUrl("~/Membership/Login")%>
This will give you the path
/xxx/Membership/Login
which you can now give to your javascript.
Using the slash makes the url relative to the root of the web server. If you want it relative to the current url, simply remove the slash character. While the tilde character has meaning in server-side controls in ASP.NET (and UNIX paths), it has no special meaning in URLs. In the context of ASP.NET, it means to make the path relative to the application, which may or may not be the web server root. In your mark up, it should be removed, either not used by you or only used in context where it is replaced by the ASP.NET framework, such as a server-side control.
When you use the form "/some/url" you are saying take me to the root of the webserver root with that url. If you want to avoid adding "xxx" to your urls you will need to either change the web server root, create a domain name and rule in IIS for that name, or use some sort of function call to generate your urls for use.
The easiest of those three is to change the webroot on the server.

Categories

Resources