I am trying to run the following javascript function
<script>
function getForm(id, element, url_route) {
console.log(id, element, url_route)
}
</script>
within
Login
Clearly there is a problem with the quotations in '{% url 'accounts:password_reset' %}'. I have tried various different approaches to escape the quotations but the webserver still throws out an error. I have tried the following but still unsuccessful:
Login
Login
I have also tried to build the url directly from the javascript function but it also doesn't work.
var url = 'accounts:password_reset';
console.log('{% url "' + url + '" %}');
The urls.py file looks like this:
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('password_reset/', views.password_reset, name="password_reset"),
]
As mentioned in the comments you should be able to pass '{% url 'accounts:password_reset' %}' directly into your javascript function's parameters. If you are seeing errors within VS Code then you can mute them by editing the settings.json with "html.validate.scripts": false
Related
I created a simple javascript on getting the URL on my browser under my application.js file:
function get_url {
var url = window.location.href;
return url;
}
Then on my helper/application_helper.rb file I called the javascript:
def get_full_url_helper
javascript_tag(
"get_url()\";"
)
end
I tried to pass this on other helper just to see if its getting the full url:
def active_url
get_full_url_helper
byebug
end
Upon using byebug instead of getting the full url on the browser it returns this weird <script>//<![CDATA[] get_url </script> thing. For some reason its not calling the right function so I can get the text URL and so something with it.
Any idea what am I missing here?
Shouldn't your function get_url be:
function get_url() { // <--- parentheses were missing in your sample
var url = window.location.href;
return url;
}
Also, a simple way to debug what the issue might be (and perhaps find out where your issue might be) is to just modify your get_full_url_helper to be:
def get_full_url_helper
javascript_tag(
"console.log('hello!');"
)
end
and then verify whether it is being invoked on your page in developer console tab in your browser.
This is the url which i am trying to hit from within .js file which contains knockout related function:
self.followAction = $.resolvePath("/People/Follow?uid=" + data.UserId);
here People is the controller and Follow is the action method, on button click, i want to send userId along so i have written this.
To resolve relative path from within javascript, i have written this function
// Fix for resolving relative paths from within js scripts
$.resolvePath = function(url)
{
var path = '#Request.ApplicationPath';
if (path != '/') return path + url;
return url;
};
But, on button click, i am getting this error: HTTP Error 404.0 - Not Found
and url is:
localhost:44305/People/#Request.ApplicationPath/People/Follow?uid=8
please tell me what should i try now. thnks in advance!
Razor code is not interpreted within JS files, hence the #Request.ApplicationPath is read as a literal string. You need to put that code somewhere where it will be executed so that your JS can read it; perhaps as a data-* attribute on an element in your View, something like this:
<!-- in a layout view... -->
<body data-app-path="#Request.ApplicationPath">
$.resolvePath = function(url) {
var path = $('body').data('app-path');
if (path != '/')
return path + url;
return url;
};
I have an asp.net mvc web application , which is deployed under /sites as follow:-
http://servername/sites/
but if i reference the URL as follow:-
url:'/ControllerName/ActionMethodName'
the result will be http://servername/ControllerName/ActionMethodName and NOT http://servername/ControllerName/sites/ActionMethodName
i usually solve this issue inside my razor view by writting the following:-
url: "#Url.Content("~/ControllerName/ActionMethodName")" . but seems that javascript does snot have the same ability. so can anyone advice?
Thanks
There are many ways to solve this, not so elegant.
I prefer to put a Hidden field in _Layout.cshtml (or any other master page)
#Html.Hidden("HiddenCurrentUrl", Url.Content("~"))
In a common js file:
var baseUrl = "";
$(document).ready(function () {
baseUrl = $("#HiddenCurrentUrl").val();
});
Then just refer Urls like this:
$.ajax({
type: 'POST',
url: baseUrl + 'solicitacoes/obtertipo/' + value
})
I'm not sure yet about this practice, but it worked for me (fixing tons of legacy code)
In your javascript file, use variables for all paths.
var ActionSubmit;
In your View include this:
<script>
ActionSubmit = '#(#Url.Content("~/ControllerName/ActionMethodName")';
</script>
I have an ASP.NET MVC3 application published to a url like this:
http://servername.com/Applications/ApplicationName/
In my code, I am using jquery ajax requests like this:
$.get(('a/b/c'), function (data) {}, "json");
When I run the application locally, the ajax request goes directly to the correct page (being an mvc route) because the local page ends with a "/" (localhost/a/b/c).
However, when I publish to http://servername.com/Applications/ApplicationName/, the trailing "/" is not always present. The url could be http://servername.com/Applications/ApplicationName, which then causes the ajax request to try to load http://servername.com/Applications/ApplicationNamea/b/c, which fails for obvious reasons.
I have already looked into rewriting the url to append a trailing slash, but A) It didn't work, and B) I feel like it's a poor solution to the problem, and that it would be better to configure the javascript urls to work properly regardless of the local folder setup.
I did try "../a/b/c" and "/a/b/c", but neither seemed to work.
Thanks in advance for the help!
Personally I tend to use a global variable of the relative URL of the server in my view like:
var BASE_URL = '#Url.Content("~/")';
Then you can do things like :
$.get(BASE_URL + 'a/b/c'), function (data) {}, "json");
I would like to add that if you want it to be totally global, you could add it to your /Views/Shared/_Layout.cshtml instead.
I ran into the same problem, and ended up creating two JavaScript functions that mirror the functionality of the MVC Url helper methods Url.Action and Url.Content. The functions are defined in the _Layout.cshtml file, so are available on all views, and work regardless of whether the application is in the root of the localhost or in a subfolder of a server.
<script type="text/javascript">
function UrlAction(action, controller) {
var url = ('#Url.Action("--Action--","--Controller--")').replace("--Action--", action).replace("--Controller--", controller);
return url;
}
function UrlContent(url) {
var path = "#Url.Content("~/--file--")";
path = path.replace("--file--", url.replace('~/', ''));
return path;
}
</script>
These can then be called like so:
var url = UrlAction('AvailableAssetClasses', 'Assessment');
var url2 = UrlContent('~/Images/calendar.gif');
Always use Url helpers when generating urls in an ASP.NET MVC application and never hardcode them. So if this script is directly inside the view:
<script type="text/javascript">
var url = '#Url.Action("a", "b")';
$.get(url, function (data) {}, "json");
</script>
And if this script is inside a separate javascript file (as it should be) where you don't have access to server side helpers, you could simply put the url in some related DOM element. For example using HTML5 data-* attributes:
<div data-url="#Url.Action("a", "b")" id="foo">Click me</div>
and then in your javascript file:
$('#foo').click(function() {
var url = $(this).data('url');
$.get(url, function (data) {}, "json");
});
and if you are unobtrusively AJAXifying an anchor or a form, well, you already have the url:
$('a#someAnchor').click(function() {
var url = this.href;
$.get(url, function (data) {}, "json");
return false;
});
On clicking hot kyes ctrl+t anywhere from my application it should redirect url to http://localhost:8080/myapp/account/create
i'm doing it by placing .js file in js folder and including that file in every page. thae content of .js file is
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href =("http://localhost:8080/myapp/account/create");
return false
});
where myapp is Controller and create is the Action . so i don't want to hard code the entire url insted, whatever the url, only the controller and action should get replaced. so that in production environment i need not to change the url. this is grails application
As I understand you problem is to pass current context path into javascript, is it?
You can remember current context name in your view (in base layout, for example), put it into your <head> block:
<script type="text/javascript">
window.pageContext = '${request.contextPath}';
</script>
and then use it from other javascript like:
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href = window.pageContext + "/account/create";
return false
});
Or, if you need to generate full path to your controller+action you have to use:
<g:createLink controller="account" action="create" />
see http://grails.org/doc/latest/ref/Tags/createLink.html for more information