I have page in which there's a function which calls a function from js file.
the code which calls function in js file:
<script language="javascript" type="text/javascript">
var qc = qc_chat;
window.onload = function()
{
qc.setup('<?php echo $p; ?>');
}
</script>
I am including qc.js file using this code:
function doThat() {
$.ajax({
url: 'http://www.example.com',
type: 'GET',
data: 'adrs='+getHost( document.domain ),
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'methodCallback',
success: function( data ) {
if( data.message == "yes" ) {
} else {
$.getScript("qc.js"); //files m including using this ajax
$.getScript("tools.js"); //files m including using this ajax
}
},
error: function( error ) {
console.log( error );
}
});
}
and i am calling doThat() using <body onload="doThat();">
but i am getting the error in console Uncaught ReferenceError: qc_chat is not defined
Thanks
2 Answers 2
Since $.getScript is asynchronous, anything that depends on the script it loads must be done in its callback function. So it should be:
$.getScript('qc.js', function() {
qc_chat.setup('<?php echo $p; ?>');
});
11 Comments
<body onload="doThat('<?php echo $p; ?>');"> and function doThat(_p) { and qc_chat.setup(_p) since the other code is a .js fileqc_chat.setup line and see what's happening.doThat() before the page loads so that it load qc.js before the page loads completey? how to do that ?doThat() in a <script> tag in the <head> instead of the onload attribute, and it will run before the body loads. But since it uses AJAX, qc.js will still not be loaded until later.When I can't to edit the place where some modules connects, I use this snippet:
var waitForqcchat = setInterval(function(){
if(typeof qcchat != 'undefined'){
clearInterval(waitForqcchat);
//here I sure, that module connected
qcchat.setup('<?=$p?>');
}
}, 200);
You should also write a logic to limit waiting if qcchat can never to be connected
qc_chatdefined. if it is not defined at all you will get this error.qc_chatby any chance defined insideqc.js?onLoadevents are going to fire before any of the async calls finish...