javaScript local script can't find function in src script - javascript

I have a javaScript source file, named LIMDU.js, that contains a var and a function, like this --
var SessionTimeOutID;
function KeepSessionAlive() {
var sessionTimeoutWarning = #Session.Timeout;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
clearTimeout(SessionTimeOutID);
SessionTimeOutID = setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
}
and in the cshtml file, I have this:
<script type="text/javascript" src="~/Scripts/LIMDU.js"></script>
<script>
$(document).ready(function () {
KeepSessionAlive();
});
</script>
but when I try to execute the code, I get the error "KeepSessionAlive" not found.
I thought that the src code would be loaded before the local script code was executed; if that's not the case, how do I refer to a function in my local script block that's defined in a src'd file?

Check your console. Your LIMDU.js file is not compiling (probably undefined #Session ?)

Related

How can I populate an embedded website form with URL parameters using Javascript?

I have a Zoho form embedded on a Squarespace site and I need to populate some fields with URL parameters in Javescript. I'm using the following code to get the parameters:
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
and then to set the parameters to variables:
var campaign1 = getUrlVars()["campaign"];
alert(campaign1);
So that gets the parameter named 'campaign' in the url and assigns it to 'campaign1'. The alert is just to show that it is working, and it is. Then I want to run this:
<script type="text/javascript" src="https://forms.zohopublic.com/....j7Q?campaign="+campaign1 id="ZFScript"> alert(campaign1); </script>
But no matter what I do I can't get that part to reference the variable in the 'src=' section, but I can reference it in the 'alert(campaign1);' immediately after.
I also tried this, which was meant to save the whole URL to a variable named 'site' and just run 'src=site', but that didn't work either.
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1
</script>
<script type="text/javascript"
src=site id="ZFScript"> alert(site);</script>
Your issue is that you are trying to write some js code where it is not parsed/rendered/executed.
The js code will be executed inside <script> tags or onEvent attributes. For instance onclick or onload.
So what you want to do is execute some js code inside a script tag that will generate a script tag with the dynamic src attribute you are trying to achieve. This is a way of doing it:
<script type="text/javascript">
// [...]
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1;
// create a script node
var scriptElement = document.createElement('script');
// set its src attribute
scriptElement.setAttribute('src', site);
// add you new script node to your document
document.body.appendChild(scriptElement);
</script>

How to call external javascript function to ClientSideEvents.Click event?

I have DevExpress().Button on a website which should take specific grid value from a focused row and pass it to external function.
Here is my button:
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnMyName";
settings.Width = 120;
settings.Height = 25;
settings.Text = "MyText";
settings.Styles.Native = true;
settings.ClientEnabled = true;
settings.ClientSideEvents.Click = "function(s, e) { gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'MyValue', OnGetRowValues); }";
}).GetHtml()
I simply can't reach OnGetRowValues function - always get the same exception:
Uncaught ReferenceError: OnGetRowValues is not defined
I have the script in the same folder as my .cshtml file and tried to reference it with <script src=""></script> in relative and absolute way. I tried to put the code to function directly between script tags to the cshtml page but nothing works and I get always the same error. The only solution which so far worked was to put the entire script as assingment to ClientSideEvents.Click but because the OnGetRowValues function is big, it will become messy and downright unpractical solution. Any help will be appreciated.
Go through Client-Side Events documentation and implement using below example:
<script type="text/javascript" src="~/Content/js/index.js"></script>
<script type="text/javascript">
function ButtonClick(s,e)
{
gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'ShipName', OnGetRowValues);
}
</script>
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnGetSelectedRowValue";
settings.UseSubmitBehavior = true;
settings.ClientSideEvents.Click = "ButtonClick";
}).GetHtml()
#Html.Action("GridViewPartial")
index.js
// Value contains the "EmployeeID" field value returned from the server, not the list of values
function OnGetRowValues(Value) {
// Right code
alert(Value);
// This code will cause an error
// alert(Value[0]);
}
Hope this help..

Javascript Dojo development script error

An interesting problem about dojo toolkit and javasacript.
I am using a visual studio to developing application
I have created a module as following and named its file as calc.js
djConfig.js
var pathRegex = new RegExp(/\/[^\/]+$/);
var locationPath = location.pathname.replace(pathRegex, '');
var dojoConfig = {
async: true,
packages: [
{
name: 'application',
location: locationPath + '/js/application'
}
};
calc.js
define(["dojo/_base/declare"], function(declare) {
return declare(null, {
Sum: function(x,y) {
return x + y;
}
}); })
Once created this file I references this file in index.html file as following,
index.html
<script type="text/javascript" src="/js/application/djConfig.js"></script>
<script type="text/javascript">
require(["application/calc"],
function(calc) {
var c = new calc();
console.log(c.Sum(1, 2));
}
);
</script>
This code is wirking at first.Calculating sum and writing in concole of browser.
But than I am changing something in calc.js (ex. return x+y-1;).
The browser is giving a script error.
If I change something in index.html page - for example type a whitespace- than script is working.
All changes in calc.js file is throwing script error, if I do not change somewhere in index.html
Even If I type a whitespace or add a line in index page, every thing is working.
Did you encounter a problem like this?

Uncaught ReferenceError: msgbox is not defined (anonymous function)

//////////////////main.js file attached
function msgbox (title,text,type,time)
{
///////////////////////////////////////////
var img = "<img src='image/"+type+".png' /> ";
$("#window .wtext").html("<table border='0'><tr><td>"+img+"</td><td>"+text+"</td></tr></table>");
$("#window .wtitle").html(title);
///////////////////////////////////////////
//$("#window .wtext").css("height",(parseInt($("#window").css("height"),10)-65)+"px");
get_center("window");
///////////////////////////////////////////
$("#window").fadeIn();
if (time!=0)
{
var t = window.setInterval(function(){
$("#window").fadeOut();
window.clearInterval(t);
},time*1000);
}
}
//////////////////myajax.js file attached
function toggle_div ()
{
msgbox("title","text","ok",3);
}
I have problem when i call msgbox from myajax.js.
how can i use my function.
it is working from another file.
i should use something for declaring global function?
you need to add both main.js and myajax.js in to your html page within tag. Then you can call directly to your function.
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript" src="myajax.js"></script>

Get content inside script as text

I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
​
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "&lt")
.replace(/>/g, "&gt")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN

Categories