I have an existing legacy aspx page loading an external JS file. I am adding functionality and have added an async function in a script block on the page. The external JS file has been modified to call the async function. No matter where on the page I load the external script it still continues to complain that the page function is not defined. I'm seriously stuck! Thanks
UPDATE:
///loading scripts
<script src="../_scripts/jquery-3.4.1.min.js"></script>
<script src="../_scripts/bootstrap-4.6.0.min.js"></script>
<script src="../_scripts/jquery.datatables.min.js"></script>
<script src="../_scripts/datatables.select.min.js"></script>
//page function
<script type="text/javascript">
$(document).ready(function () {
async function providerPopUp() {
await $.ajax({
url: '../Provider/PreCert_PrvSearch.aspx',
method: 'get',
data: { typeOfSearch: typeOfSearch, coIdNbr: coIdNbr },
dataType: 'json',
success: function (response) {.......
//load external script after page script
<script src="../_scripts/PreCert_Create.js"></script>
//call to page function added to external js file
function Pop_Modal_Window_NPI (){
providerPopUp()
.then((result) => {
console.log('result: ' + result);
retPrv = result;
})
External JS file function Pop_Modal_Window_NPI is triggered onblur of a text box
Result is Uncaught ReferenceError: providerPopUp is not defined
at Pop_Modal_Window_NPI (PreCert_Create.js:169)
at HTMLInputElement.onblur (PreCert_Create.aspx?...parameters)
Pop_Modal_Window_NPI() calls the function providerPopUp(), but the latter is inside an enclosure and so isn't in the scope of the call.
You can get around this by adding the function to the window namespace:
window.providerPopUp = async function() {
...
};
And then the call inside Pop_Modal_Window_NPI becomes:
window.providerPopUp()
(You don't even need to prefix window to the function call, I just do it for consistency)
Related
I have a trigger button on my page that activate to load code from another htmldoc into a div on my page.
Works great like here:
https://blog.kulturbanause.de/2012/12/inhalte-per-ajax-jquery-nachladen/
I take this code:
<script>
function kb_source_2_target() {
$.get('source.html', function(data) {
$('#target').html(data);
})
}
</script>
Now I want my trigger-button to start a second function after loading the code in the div.
in the loading code there is a div, f.e. class="divtofadeoutafter loading"
i want to trigger now the loading and then the fadeout of an other div in the loaded content.
Can I do this with a callback?
I tried this:
<script>
function kb_source_2_target() {
$.get('source.html', function(data) {
$('#target').html(data,
function callback(){
$(".divtofadeoutafterloading").fadeOut();
}
);
})
}
</script>
thanks for any idea
stefan
There is no callback in html() so you just need to do it inline since it is a synchronous operation.
function kb_source_2_target() {
$.get('source.html', function(data) {
$('#target').html(data)
$(".divtofadeoutafterloading").fadeOut();
})
}
When using $.getScrtip it does not cache your dynamically loaded js, so i have this custom one.
jQuery.loadScript = function (url, callback) {
var load = true;
//check all existing script tags in the page for the url
jQuery('script[type="text/javascript"]')
.each(function () {
return load = (url != $(this).attr('src'));
});
console.log('load is ' + load);
if (load) {
//didn't find it in the page, so load it
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'script',
cache: true,
ifModified: true,
success: callback
});
} else {
//already loaded so just call the callback
if (jQuery.isFunction(callback)) {
callback.call(this);
};
};
};
it works on caching part, however it does not work when i am refreshing the page using f5 and 304 is received on next attempt to dynamically load js. i get function undefined for a function defined inside the loaded js. here is how i call this (this same code perfectly with $.getScript if replaced $.loadScript)
function getvm() {
return $.getScript("Scripts/ViewModel/cachedvm-1.0.0.js")
}
function functionthatinvokesjsload() {
$.when($.get(myUrl), getvm())
.done(function(a1, a2) {
initializeVm();
});
}
Error i am getting is initializeVm() is not defined when i get 304 on js load. it works the first time. but if i later manually do it in browser debug window it does find that function. it seems to be i am trying to invoke the js before its loaded to DOM but not sure why that is happening.
i had to use
jQuery.loadScriptNoCallBack = function (url) {
return $.ajax({
type: 'GET',
url: url,
dataType: 'script',
cache: true,
ifModified: true
});
};
My page makes an Ajax call which returns some HTML to embed in the page and a script to run, attaching JQuery tooltips to various elements of the embedded HTML. The HTML and script are returned as JSON objects by my Django backend, and appear OK in the page, but the Javascript doesn't seem to work when I evaluate it:
$.ajax({
type: "GET",
url: "/url/to/ajax",
data: {
"foo": bar
},
success: function (data) {
$("#my-table").html(data['html']);
// alert(data['script']); // this works: I can see the script
eval(data['script']);
},
error: function () {
$("#my-table").html('');
}
});
The script itself looks like a series of expressions such as:
$(".foobar1").tooltip({
content: "The <em>foo</em> to the <strong>bar</strong>.",
tooltipClass: "tt-ref",
show: null,
close: function (event, ui) {
ui.tooltip.hover(
function () {
$(this).stop(true).fadeTo(400, 1);
},
function () {
$(this).fadeOut("400", function () {
$(this).remove();
})
});
}
});
where foobar1 is a class in the HTML just added to the #my-table HTML.
Can anyone see where I'm going wrong here? Both jquery and jquery-ui are loaded on my page.
You don't need to eval anything, let browser execute it. For this create script element, set its content and append it to DOM:
success: function(data) {
$("#my-table").html(data.html);
$('<script>').html(data.script).appendTo('body');
},
Another, probably better option is to make script a part of the returned HTML.
You might try :
eval("data['script']");
I want to create a module loader for javascript files using $.getScript but since the loading of the scripts is then asynchronously when I put a function call of a module inside the document they may be called before the module was loaded. Is there any way to avoid this situation maybe by putting the function call on hold until the module was loaded successfully?
framework.core.js:
var Framework = $.extend(Framework, Framework.Core = {
modules: [
'Module1',
'Module2'
],
init: function () {
$.each(modules, function (index, value) {
$.getScript('framework.' + value.toLowerCase() + '.js', function () {
});
});
}
});
Framework.Core.init();
site.html:
<html>
<head>
<script src="framework.core.js"></script>
<script>Framework.Module1.functionCall();</script> // Call a function independent of the completion of the framework.core.js loader
</head>
...
You will need to open the success callback for the depending functions to hook on it. You will not be able to defer the execution of those following functions to wait for the Module (unless you would insert the script via document.write), so the callback is necessary. Best, just make the Deferred object (returned by the ajax function) public. Also, you should not use jQuery.getScript/ for that task at all, because it prevents caching.
var Framework = $.extend(Framework, Framework.Core = {
// The "Core" property seems pretty useless, by the way ^^
modules: [
'Module1',
'Module2'
],
loads: {},
init: function () {
$.each(this.modules, function(index, value) {
this.loads[value] = $.ajax({
url: 'framework.' + value.toLowerCase() + '.js',
cache:true,
dataType:"script"
});
});
}
});
Framework.init();
<html>
<head>
<script src="framework.core.js"></script>
<script>Framework.loads.Module1.then(function() {
functionCall();
}); // Call a function as soon as the module is loaded
</script>
</head>
...
I have this js file serving from some domain say foobar.com
at http://foobar.com/static/js/main.js:
$(document).ready(function() {
function foobar(bar){
$.ajax({
url: "/site/foo/",
data: {'foo':bar},
dataType: "jsonp",
crossdomain: !0,
success: function (data) {
alert(data);
},
error: function () {
}
})
}
});
On barfoo.com on some url, I have something like this:
<script src='http://foobar.com/static/js/main.js' type='text/javascript'></script>
<script type='text/javascript'>foobar('123456')</script>
When I hit that url : it says
Uncaught ReferenceError:foobar is not defined (anonymous function)
How to access function from other domains?
You've defined "foobar()" inside the "ready" handler. It's therefore a local variable in that function, and invisible outside it.
You could add this to the end of the "ready" handler:
window['foobar'] = foobar;
and then it'd be visible globally.
By the way this is something that can bite at jsfiddle because it (by default) will wrap code in a "load" handler. Thus, if you copy/paste from a JavaScript file included in the <head>, a function that would be global in that context ends up not global in the fiddle.
Your function is not visible globally as pointed out by Pointy. But you are also loading a script and calling a function defined by the ready() function. I guess it's possible ready() may not have been called when your script calls foobar() which would generate the same error. I would recommend you set a global value in your script and then use that variable in the ready() function.
Set the value in the script:
<script src='http://foobar.com/static/js/main.js' type='text/javascript'></script>
<script type='text/javascript'>var bar = '123456'</script>
Then you can use it in the ready() function.
$(document).ready(function() {
$.ajax({
url: "/site/foo/",
data: {'foo':bar},
dataType: "jsonp",
crossdomain: !0,
success: function (data) {
alert(data);
},
error: function () {
}
});
});
If you want to define a function so you can use it again you can call it in ready() but make sure you set the global variable bar to what you want.
window.foobar = function() {
$.ajax({
url: "/site/foo/",
data: {'foo':bar},
dataType: "jsonp",
crossdomain: !0,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
$(document).ready(function() {
foobar();
// other stuff
});