JavaScript function can't be run in external file - javascript

I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?
HTML:
<head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}
function save() {
A("msg");
var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...
my.js:
function A(msg) {
scroll(0,0);
var outerPane = document.getElementById('FreezePane');
var innerPane = document.getElementById('InnerFreezePane');
if (outerPane) outerPane.className = 'FreezePaneOn';
if (innerPane) innerPane.innerHTML = msg;
}
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}

The safest thing to do is wrap the code in the head in a window.onload handler like this...
<head>
<script type="text/javascript">
window.onload = function(){
// your external files are guaranteed to be loaded now
// you can call A or B
}
</script>
</head>
onload is only fired after all external scripts have been loaded.
Here is a full example...
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
A()
B()
}
window.onload = function() {
save()
}
</script>
</head>
<body>
The content of the document......
<script src="./external.js"></script>
</body>
</html>
external.js
function A() {
alert('A ran')
}
function B() {
alert('B ran')
}
NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.
By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.

Add your external file before the script tag contains your "save" function.
<script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
function save(){
A();
B();
}
</script>

Related

How to capture URL params within wordpress and pass along in javascript

My lack of experience with both Wordpress and Javascript is tripping me up.
I have a Wordpress page that has a Jotform embedded using this tag:
<script type="text/javascript" src="https://form.jotform.com/jsform/FORMCODE"></script>
But I have a value coming into my Wordpress through the URL that I need to pass along in the embedded Jotform's URL. I cannot figure out how to do that. Do I want to use PHP? Javascript?
I tried this, which didn't work at all:
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
Thanks for any help!
To add a javascript code to a WordPress page you need the page id else the js code will be on all the pages.
You can either add the js code to the head of the page likes so:
add_action('wp_head',function () {
// 10 is the page id;
if (is_page ('10')) {
?>
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
<?php
}
}
);
Then put the js code on the footer like so:
add_action('wp_footer',function () {
// 10 is the page id;
if (is_page ('10')) {
?>
<script type="text/javascript">
function getURL(){
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
let pair = params_arr[0].split('=');
return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>
<?php
}
}
);
Whichever snippet you pick should be added to your theme functions.php or code snippet plugin if you have one

How to include external script into <script>?

Inside my JS function I need to add this:
< script src=https://xxxx.com/c3.js type="text/javascript" async defer>< /script>
How to edit the code the right way?
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
<script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
console.log(ab_id_transakce);
}
</script>
If I understand your question correctly, you are trying to add a script tag to the DOM. It seems that you are trying to add the HTML script tag in the Javascript function, which will not work. What you can try is:
Add the script tag directly in the HTML like this:
<script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
console.log(ab_id_transakce);
}
</script>
Add the script tag dynamically
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
console.log(ab_id_transakce);
var script_tag = document.createElement("script");
script_tag.src = "https://xxxx.com/c3.js";
script_tag.type = "text/javascript";
script_tag.async = true;
script_tag.defer = true;
// in case you want to add the script tag to the <head>
document.head.appendChild(script_tag);
// in case you want to add the script tag to the <body>
document.body.appendChild(script_tag);
}
</script>

Uncaught TypeError: google.script.run.doSomething is not a function

I am trying to check if the input name is already in a Google Sheet. However, I am getting this error:
Uncaught TypeError: google.script.run.doSomething is not a function.
Here is my Index.html file.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value=""> // Getting value here
<button onclick="checkName()">Check if available</button> //Calling function is is causing the error.
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
google.script.run.doSomething();
}
function checkNameCS(checkNameSSReturn) {
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
function doSomething () {
var nameGiven = document.getElementById("meetingTitle").value;
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
prompt("name " + name);
var spreadsheetId = ''; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (!values) {} else {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
checkNameCS("");
prompt("name2 " + " ");
return;
}
nameVerified = true;
prompt("name2 " + name);
checkNameCS(name);
return;
}
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
</script>
</body>
</html>
I tried debuging it with prompts but with no success. It seems like the function do something is properly called. But the code stops working aftergoogle.script.run.doSomething();.
I have looked at the documentation for successhandlers but they dont solve the issue either.
How about this modification?
Issue of your script:
doSomething() of google.script.run.doSomething() is required to be Google Apps Script.
In your script, doSomething() is put in HTML (index.html), and a method for using Google Apps Script is included. When google.script.run.doSomething() is run, doSomething() cannot be found at Google Apps Script (code.gs). By this, such error occurs. And if doSomething() is run at HTML side, also an error occurs at Sheets.Spreadsheets.Values.get(), because Sheets.Spreadsheets.Values.get() is the method of Advanced Google Services with Google Apps Script.
If you put it to Google Apps Script (code.gs), Javascript which is used at the script of doSomething() is required to be modified.
Modified script:
In this modification, your script was separated to Google Apps Script (code.gs) and HTML (index.html). var nameGiven = document.getElementById("meetingTitle").value; and checkNameCS(name); are used in index.html.
By the way, before you run this script, please enable Sheets API at Advanced Google Services.
Google Apps Script: code.gs
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function doSomething (nameGiven) {
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
var spreadsheetId = '###'; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (values) {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
return "";
}
nameVerified = true;
return name;
}
HTML: index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value="">
<button onclick="checkName()">Check if available</button>
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
var nameGiven = document.getElementById("meetingTitle").value; // Added
google.script.run.withSuccessHandler(checkNameCS).doSomething(nameGiven); // Modified
}
function checkNameCS(checkNameSSReturn) {
console.log(checkNameSSReturn)
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
</script>
</body>
</html>
Reference:
Class google.script.run

Javascript function not firing - body onload

OK, so I have a page that has the following, the function creates a drop down populated with information as q15:
The below code fires when a user selects an option from the drop down q14:
onchange="configureDropDownLists(this,'q15')"
The same function is called when the page loads using the onload option:
<body onload="configureDropDownLists('q14','q15');check();">
These are the two functions used:
function configureDropDownLists(q14,q15) {
if (langu.languag=='English'){
var not = new Array('');
var australia = new Array('Perth','Brisbane','Sydney (Frenchs Forrest)','Sydney (Auburn)','Melbourne','Adelaide','Auckland');
}
switch (q14.value) {
case '':
document.getElementById(q15).options.length = 0;
for (i = 0; i < not.length; i++) {
createOption(document.getElementById(q15), not[i], not[i]);
}
break;
case '1':
document.getElementById(q15).options.length = 0;
for (i = 0; i < australia.length; i++) {
createOption(document.getElementById(q15), australia[i], [i+1]);
}
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
Finally, this messy code is in the header section of the page:
<script type="text/javascript">
window.results = ["<?php echo implode ('","', $results); ?>"];
</script>
<script type="text/javascript">
function selected(){
var res = 'test';
document.getElementById("test").value = res;
alert(res);
}
</script>
<script type="text/javascript">
var langu = {
languag : '<?php echo $lang; ?>'
}
</script>
<script src="main.js" type="text/javascript"></script>
<script src="javascripts/scriptaculous.shrunk.js" type="text/javascript" charset="ISO-8859-1"></script>
<script src="javascripts/page2_validation.js" type="text/javascript"> </script>
The code fires correctly using the onchange call when a user selects q14. In addition, on q14 there is PHP code that auto selects an option if the user has visited the page before - in this instance I want the function to run and create q15 when the page loads, hence I'm trying to use onload, however, I simply cannot get it to fire.
Any ideas and suggestions welcomed, please!
H.
"this" is referring to the select so you need to pass a select object
Do this instead of inline
window.onload=function() {
configureDropDownLists(document.getElementById('q14'),'q15');
check();
}
You have passed a string as q14 when you intended to pass an element.
Having said that, this would be a lot easier to debug if you gave us a jsfiddle.net workspace to tinker with.

updating a parameter within location (src) using JavaScript

How can I parse the value of status = 'logged-out' to the 3 tags below it, updating the value of login_status = 'logged-out'?
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/adserver/ndm/js.php?position=header-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
Keep in mind, there also heaps of other script tags on the page, so to identify the relevant ones. I got this function.
function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
if (scripts[i].src.indexOf(name) > -1)
return scripts[i].src;
}}
Therefore to find the relevant script tags I want, i call the function - getScriptSourceName('foo.com');
How can I then update the login_status parameter's value to use the one declare at the very top?
I think this should work (below the HTML file for testing).
Look at changeStatus method (I triggered it by button click for testing).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>
<script>
function changeStatus(name)
{
var scripts = document.getElementsByTagName('script');
var scriptsToChange = [];
for (var i = 0; i < scripts.length; i++)
{
if (scripts[i].src.indexOf(name) > -1)
{
var oldSrc = scripts[i].src;
var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
scripts[i].setAttribute("src", newSrc);
scriptsToChange.push(scripts[i]);
}
}
for (var k = 0; k < scriptsToChange.length; k++)
{
document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
}
}
</script>
</head>
<body>
<button type="button" onclick="changeStatus('foo.com')">Change status</button>
</body>
</html>

Categories