I need jQuery to post to a relative url (currently its posting to the root).
Structure:
- site url:
localhost/myApp - Form url:
Account/Login - actual server url:
localhost/myApp/Account/Login<- need it here - posting to url:
localhost/Account/Login
Form:
<form id="login" action="Account/Login" method="POST">
</form>
jQuery:
$.post($el.find('form').attr("action"), $el.find('form').serialize(), function(resp) {
});
I need to be able to put this app in any URL and it works, so if its hosted at www.site.com/dir1/dir2/, then it should post to www.site.com/dir1/dir2/Account/Login.
Note, this is a single page app. So the form is located at localhost/myApp.
Headers Info:
Request URL:http://localhost/Account/Login
Request Method:POST
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:19
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/myApp
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
X-Requested-With:XMLHttpRequest
Although you’re loading /myApp, it’s clear that some form of redirection is taking place that is dropping the client at the root / path:
Thus, in your action, add the following to the action attribute:
As an aside, you either have a 301/302 redirect that is rewriting the URL to
http://localhost, or you’re not really visitinghttp://localhost/myApp, or you could possibly have a<base>HTML element that is causing your relative URLs to get thrown off. Without seeing all of the HTML, it’s difficult to say for sure, but changing the path in the action will connect your form to the server.If the root of your application changes from platform to platform, consider using the
<base>HTML element to avoid needing to change all of your URLS. With<base>, you simply make the change in 1 place in the HTML.For more information, please see the Mozilla Developer Center article on the base HTML element:
Also, while information from W3Schools should be digested with some scrutiny, I list the page on the base HTML element here, simply because they have a better example than MDC:
Here is the obligatory W3Fools link.
NOTE: The base element must come before any other element that refers to the URLs that are modified by the base element.