I would like to read a file (server-side) using jQuery. I have tried code supplied by multiple sites and it has not worked.
The code I tried last is:
jQuery.get("users/" + get("user") + "/display.txt", function(data) {
fullName = data;
});
However the variable 'fullName' (which is previously declared in the code) comes out as 'undefined'. How can I get this to work?
EDIT: Full code (excluding CSS)
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function get(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var fullName;
var file = "users/" + get("user") + "/display.txt";
jQuery.get(file, function(data) {
fullName = data;
});
</script
</head>
<body bgcolor="#B2C2F0">
<div class="window">
<div class="rightCorner">
<span><script type="text/javascript">document.write(fullName)</script></span>
</div>
</div>
</body>
</html>
You can't modify fullName var with data value inside that function and read it outside.
If you need to use that info outside the function, you need to export the data value within another function.
Something like:
var fullName = "not-set";
console.log('fullName is:', fullName); // not-set
function set_fullName( data ) {
fullName = data;
console.log('fullName is:', fullName); // must be `Levi` now
}
jQuery.get("users/" + get("user") + "/display.txt", function(data) {
set_fullName(data);
});
You're probably just trying to access fullname before the ajax call finishes.
Try this:
var fullName = "";
function getUserName(username){
jQuery.get("users/" + get("user") + "/display.txt", onGetComplete);
}
function onGetComplete(data){
fullName = data;
continueProgram();
}
function continueProgram(){
console.log(fullName);
}
getUserName();
Related
I want to to call a function file2Function(getValue) of a file (page2.js) from another JavaScript File (page1.js) to open new page in browser and display some data on it using parameter passed viamyFunction1(e) into file2Function as file2Function(itemFromItems). So file2Function(getValue)should take value of var itemFromItems and should display on page2.html. But it is displaying "undefined" for getValue. Kindly help me finding out where I am doing Mistake. Thank You.
// page1.js
function file1Function()
{
var secPage1 = document.getElementById("page1Section");
var heading = document.createElement("h4");
var anchor= document.createElement('a');
anchor.setAttribute('href',"#");
anchor.innerText = "Click Me";
anchor.addEventListener("click", myFunction1);
heading.appendChild(anchor);
secPage1.appendChild(heading);
anchor.id=1;
function myFunction1(e) {
var itemFromItems = e.currentTarget.getAttribute("id");
console.log("item",itemFromItems);
file2Function(itemFromItems);
}
}
// page2.js
var globalVar;
function file2Function(getValue)
{
console.log("getValue",getValue);
window.open("page2.html");
// window.open("https://www.google.com/");
globalVar=getValue;
console.log("globalVarNow",globalVar);
}
function loadDynamicData()
{
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
<!-- page1.html -->
<!DOCTYPE html>
<html>
<head>
<script src="js/page1.js"></script>
<script src="js/page2.js"></script>
</head>
<body onload="file1Function()">
<h3>This is page1</h3>
<section id="page1Section">
</section>
<script>
</script>
</body>
</html>
<!-- page2.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="loadDynamicData()">
<h3>This is page2</h3>
<section id="page2Section">
</section>
<p id="paraId"></p>
<script src="js/page2.js"></script>
</body>
</html>
The problem is that globalVar is a global variable, but the value you are assigning to it in file2Function() is accessable only within its scope, that is why you are getting undefined, because loadDynamicData() has no access to the new value of globalVar.
You could call loadDynamicData() from file2Function() and pass getValue as an argument, but since you need to open page2 before executing loadDynamicData() it won't work.
What I suggest is you pass getValue along with your URL as a query parameter and get it from inside loadDynamicData(), it'll work fine.
SOLUTION:
function file2Function(getValue)
{
window.open("page2.html?value="+getValue);
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var url_string = window.location.href
var url = new URL(url_string);
var globalVar = url.searchParams.get("value");
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
If you want to hide the values you can use sessionStorage instead of query parameters:
function file2Function(getValue)
{
sessionStorage.setItem('value', getValue)
window.open("page2.html");
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var globalVar = sessionStorage.getItem('value')
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
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
My question is: How can i use variable ime in Handlebars template(sadrzaj-template)?
My HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>2 kolokvijum</title>
</head>
<body>
Ime autora: <input id="imeAutora" type="text" value="..."><br><br>
<button id="btnAutor" type="submit" onClick="autorIme()">Prikazi</button><br><br>
<script src="handlebars-v4.0.11.js"></script>
<script id="sadrzaj-template" type="text/x-hanldebars-template">
{{#each knjige}} {{#equal autor ime}}
<h2>{{naslov}}</h2>
<img src="{{slika}}">
<h4>{{brojstrana}} strana</h4>
<h3>Autor: {{autor}}</h3>
<h3>cena: {{cena}}</h3>
{{/equal}} {{/each}}
</script>
<div id="sadrzaj"></div>
<script>
function autorIme() {
var ime = document.querySelector("#imeAutora");
console.log(ime.value);
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'json.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
function createHTML(knjigeData) {
var knjigeTemplate = document.querySelector("#sadrzaj-template").innerHTML;
var compiledTemplate = Handlebars.compile(knjigeTemplate);
var ourGeneratedHTML = compiledTemplate(knjigeData);
var knjigeContainer = document.querySelector("#sadrzaj");
knjigeContainer.innerHTML = ourGeneratedHTML;
};
};
</script>
<script>
Handlebars.registerHelper('equal', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if (lvalue != rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
</script>
</body>
</html>
You need to pass it as an argument (as a field in the argument object actually) to the compiled template (which is actually a function). In your case, it is compiledTemplate(). Since you're already passing knjigeData to it, just add your variable as a field to the data object which eventually becomes knjigeData.
var data = JSON.parse(ourRequest.responseText);
data.ime = ime.value;
createHTML(data);
Now you can use it like {{ime}} if you want the variable's direct value in the template. Or you can use it like how you've done, like {{#equal autor ime}}
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>
I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>