I have some javascript that's referencing /jobs/GetIndex in an MVC project. This works great when I run it locally because I have a Controller called JobsController. When I deploy it, I deploy the application to a 'Jobs' subfolder, which means the URL should become http://site/jobs/jobs/GetIndex but it's going to http://site/jobs/GetIndex, I presume because the javascript doesn't know what the 'root URL' is, and uses the site as the root. How can I get it to work in both environments?
If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use / as the first character of your url.
var urlToJobIndex2= "/jobs/GetIndex";
Here is an alternate approach if you want more than just the app root (Ex : Specific urls( built using mvc helper methods such as Url.RouteUrl etc)
You may use the Url.Content helper method in your razor view to generate the url to the app base, assign it to a javascript variable and use that in your other js code to build your other urls.
Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
If you want to get url to a specific action method, you may use the Url.Action or Url.RouteUrl helper methods.
So in your razor view (Layout file or specific view), you may do this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
myApp.Urls.jobIndexUrl= '#Url.Action("GetIndex","jobs")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in your PageSpecificExternalJsFile.js file, you can read it like
var urlToJobIndex= myApp.Urls.jobIndexUrl;
// Or With the base url, you may safely add the remaining url route.
var urlToJobIndex2= myApp.Urls.baseUrl+"jobs/GetIndex";
Here is a detailed answer about the same , but using this in a specific page/view
Angular Js
You might need the correct relative url(s) in your angular controller / services / directives.The same approach will work for your angular code as well. Simply build the js namespace object and use the angular value provider to pass the data to your angular controllers/services/directives as explained in this post in detail with example code.
Add <base href="/jobs"> to your head tag. It will specify the root.
This is further explained here https://docs.angularjs.org/guide/$location
Related
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?
static-pages-server.js:
app.get('/index', function(req, res) {
var name = "hello";
res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
});
index.html:
<script type="text/javascript">
console.log(name);
</script>
Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.
<script type="text/javascript">
console.log(<%=name%>);
</script>
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.
Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html
Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.
It would allow you to pass data directly from your routes into the page you are rendering.
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.
Simply modify your index.html like this:
<script type="text/javascript">
let name = "{{name}}";
console.log(name);
</script>
here is the answer How do I use HTML as the view engine in Express?
what you will need is a view engine package in your app. there are many view engines currently available.
then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.
check out esj or pug (ps pug is my personal favourite )
Using Joomla to create my site. Let say my site is located at
https://domain.com/directory/siteName
I want to get this path in javascript on any page rendered on my site. The issue is, following internal sub menus and site's different settings, the path comes to be any one like these-
https://domain.com/directory/siteName/anyMenu/index.php
https://domain.com/directory/siteName/index.php
https://domain.com/directory/siteName/index.php?option=com_content&id=9
https://domain.com/directory/siteName/anyMenu
https://domain.com/directory/siteName/anyMenu.html
I have tried some solutions like-
var re = new RegExp(/^.*\//);
alert(re.exec(window.location.href));
It truncates the last node as index.php in case 1, also
var dummy = new Image;
dummy.src = '$';
alert(dummy.src.slice(0,-1));
does the same thing. So is there any way to get exact address where site is located using javascript only? Also the result must be generic for any site as if it is applied in any extension then that extension can be installed in any site with any level of directory structure.
I require this as I am using a js file which is internally registering another js file. So path for this, to be registered js has to be given in first js
You can use Joomla's JURI::base() function for that. Remember it's php. so you could do something like:
$document = JFactory::getDocument();
$document->addScriptDeclaration('var base = \''.JURI::base().'\'');
You can now use the base variable in your JS script. Remember to add it to the document after the declaration above.
this should be simple but after extensive googling I havent found an answer.
I use cloudfront as a CDN for my web app. I would like to configure the cloudfront url to a single file, as it might change in the future. I am trying currently to pass the value to the the templates as they use some images via css style background. I have found out that one solution would be to put in the scope in every controller, but there so many of them, and including this to all would make the code more possible for errors if it is forgotten.
So, this is a code example I have tried:
app.js:
.constant('CDNurl', 'https://xxxxxxxxxxx.cloudfront.net/')
main.js:
$rootScope.CDN = CDNurl;
navbar.html:
<div class="avatar__image"
ng-style="{'background-image':'url(' +
$root.CDNurl + currentUser.profileImage+')'}">;
does not work. If I include it in the navbar controller it of course works, but I need to pass it globally.
So what is the correct way of doing this? Configure something and reach it from templates?
If you have a parent controller at the top of the DOM and in that you set $rootScope.CDN = CDNurl;, then you can access CDNurl is available in all the child views.
Or another option might be to use run (I haven't tried this):
var app = angular.module('module', []);
// run blocks
app.run(function($rootScope, CDNurl) {
$rootScope.CDN = CDNurl;
});
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} });
Just explaining my question in short.
I have asp.net website with root structure as following
root Directory->
Admin
abc.aspx
xyz.aspx
index.aspx
Now I want to redirect from abc.aspx to index.aspx.
I'm using JavaScript as
window.location = "../index.aspx";
but found no any luck.
This is a very odd trick. But it works.
Have a hidden field in the page. This needn't be a server control. (Or if you want, you can even do without one.). For brevity sake I am assuming you've used a server HiddenField control, called hfNavUrl. Do something like this.
hfNavUrl.Value = Me.ResolveUrl("~/index.aspx")
Once this renders you get the full url. Find the hidden field value in javascript and work your javascript code:
window.location.href = document.getElementByValue('hfNavUrl').value;
Update: Doing it w/o using controls
There are two ways about this. However, you'd have to embed the code in your page markup file (i.e. the *.aspx file). The javascript way is something like holding the url into a variable.
var url = '<%= Me.ResolveUrl("~/index.aspx") %>';
You can now make use of the value inside of this variable at a later point of time.
Alternatively, you can simply have a <a> element with its href set directly:
Home
Ps: Me.whatever is the vb.net way of doing things. Replace it with this if you are working with c#
Try using "window.location.replace('/index.aspx')"
You issue will be resolved by one of the below solutions from java script by providing the type of application.
If Application created as Website
windows.location='/index.aspx';
and
If Application created as Virtual directory
windows.location='/[Virtual Directory Name of Root Folder]/index.aspx';