Chrome won't load simple JavaScript - javascript

My JavaScript inside the head tag:
<script type="text/javascript">
function over1() {
var img1 = document.getElementById("1").src;
document.getElementById("big").src = img1;
}
function out() {
document.getElementById("big").src = "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/shop-icon.png";
}
function london() {
var city = document.getElementById("city").value;
var check = city.toLowerCase();
var province = document.getElementById("province").value;
if (check == "london" && province == "ON") {
alert("Visit our company travel store at Masonville Mall!");
}
}
function  checkinput()  {
var email = document.contest.email.value;
var emailcheck = email.search("#");
if (!document.contest.name.value)  {
alert("Enter a name!")
} else {
alert("Thank You " + document.contest.name.value + " " + document.contest.lastname.value + " For Entering The Contest!")
window.open(calculator.html,'_blank');
}
}
</script>
I have the simple JavaScript inside the HTML file, but Chrome won't read it. In Inspector View, it throws ReferenceErrors for all my functions. Please help.

Why do you say that, those are all functions, nothing is invoked from these functions. call the functions and see if they are invoked correctly or not
checkinput();
over1();
/* the rest of them */

Related

How can i use same private variable in 2 functions

So im having 2 functions. Problem is in styep_id variable. I know that i can just declare it in second functions, but then he wont take out data from first function. So the question is how i can use the same variable without lost data on him
P.S It shouldn't be public variable, cos it wont work. It wont hold the data.
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// Ja ir tikko kā pievienots, tad tikai izmetīsim ārā no DOM
if (!styep_id == "") {
estpt_action_links_td_jqobj = $(this).parent();
estpt_tr_jqobj = estpt_action_links_td_jqobj.parent();
stya_id = $("td.service-type-est-position-estimate-position-type-name>input.stya-id-for-styep", estpt_tr_jqobj).val();
estpt_tr_jqobj.remove();
show_stya_delete_link_if_possible(stya_id);
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"));
}
}
And
function save_configuration(){
var estpt_for_estpgt = "";
// Pārbaudam vai visām tāmes pozīciju grupām ir norādītas tāmes pozīcijas
$('.estpt-for-estpgt').each(function(){
if ($(this).find('tr.action_record_tr').size() == 0){
estpt_for_estpgt = this;
return false;
}
})
if (estpt_for_estpgt == "") {
var form = $(this).closest('form');
form.submit();
// Dzēsīsim ārā no datu bāzes
authenticity_token = $("#authenticity_token").val();
request_url = "/service_type_est_positions/" + styep_id + "/destroy_from_service_type_config";
$.post(request_url, { authenticity_token: authenticity_token}, process_service_type_est_position_delete, "json");
} else {
$.alerts.okButton = 'Labi';
jError("Vismaz vienai Tāmes pozīciju grupai nav norādīta neviena Tāmes pozīcija!", "Kļūda");
}
return false;
}
function remove_estpgt_if_has_no_estpt(estpgt_id) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
call your second function within the first and pass the variable as an argument:
function delete_estimate_position_type() {
save_configuration(styep_id)
}
function save_configuration(id){
request_url = "/service_type_est_positions/" + id + "/destroy_from_service_type_config";
}
You can use like this
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
// Get it from argument.
function remove_estpgt_if_has_no_estpt(estpgt_id,styep_id ) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
Another option is set it in hidden field.
// html
<input type = "hidden" id="styep_id_newval" value="">
// End of html
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
$("#styep_id_newval").(styep_id.val());
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
Now you can easily access code using anywhere.
$("styep_id_newval").val();

Google apps script function returns undefined in html

I am building an add-on for google docs (Just for practice) that will act like email. I already incorporated sending, receiving, deleting, and viewing messages. I added the code needed for a UI modal dialog, but one of the functions is only returning undfined. I tested this function in the code.gs file, and it worked perfectly. Here is a section of code.gs:
function onInstall() {
var html = HtmlService.createHtmlOutputFromFile('Startup').setWidth(350).setHeight(170);
DocumentApp.getUi().showModalDialog(html, 'New account:');
}
function testCheck() {
var ui = DocumentApp.getUi();
ui.alert(checkUsername(ui.prompt('').getResponseText(), ui.prompt('').getResponseText()));
}
function checkUsername(un, em) {
var i; var a; var is;
var props = PropertiesService.getScriptProperties();
if (props.getProperty(un) == null) {
is = true;
} else {
return 'This username is taken!';
}
if (em.length == 0) {
return true;
} else {
var len = (em.match(/#/g) || []).length;
if (len == 1) {
if (props.getProperty(em) != null) {
return 'Someone has already registered this email address as ' + props.getProperty(em);
} else {
return true;
}
} else {
if (em.indexOf(', ') != -1) {
em = em.split(', ');
} else if (em.indexOf('; ') != -1) {
em = em.split('; ');
} else if (em.indexOf(' + ') != -1) {
em = em.split(' + ');
} else if (em.indexOf(';') != -1) {
em = em.split(';');
} else if (em.indexOf(',') != -1) {
em = em.split(',');
} else if (em.indexOf('+') != -1) {
em = em.split('+');
} else if (em.indexOf(' ') != -1) {
em = em.split(' ');
} else {
return 'Please separate your email addresses with a comma, space, or semicolon.';
}
for (i = 0; i < em.length; i++) {
a = em[i];
if (props.getProperty(a) != null) {
return 'Someone has already registered ' + a + ' as ' + props.getProperty(a);
}
}
return true;
}
}
}
Here is the html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
Username:<br>
<input type='text' id='user' style='width:350px' maxlength='12'/><br>
Other email addresses:<br>
<textarea id='extras' style='width:350px' rows='2'></textarea><br>
<span class='error' id='err'></span><br>
<button class='action' onClick='check()'>Next</button>
<button onclick='group()'>Groups</button><br>
<script>
function check() {
var un = document.getElementById('user').value;
var em = document.getElementById('extras').value;
var fail = document.getElementById('err');
var is = google.script.run.checkUsername(un, em);
if (typeof is == 'string') {
fail.innerHTML = is;
} else {
google.script.host.close();
google.script.run.setAccount(un, em);
}
}
function group() {
var un = document.getElementById('user').value;
var em = document.getElementById('extras').value;
var is = google.script.run.checkUsername(un, em);
if (typeof is == 'boolean') {
setGroupAddress(un, em);
} else {
document.getElementById('err').innerHtml = is;
}
}
</script>
</body>
</html>
Update: I completely retyped the functions, but the program continues to return undefined. All inputs are the correct values, and the function returns information correctly in a ui.alert() box.
I figured it out after completely reading the Google Apps Script Documentation. The google.script.run.function() API does not return a value. In order to fetch data from a script, you must have the script generate raw HTML, and create a dialog with an HTML string.
Due to security considerations, scripts cannot directly return HTML to a browser. Instead, they must sanitize it so that it cannot perform malicious actions. You can return sanitized HTML using the createHtmlOutput API
function doGet() {
return HtmlService.createHtmlOutput('<b>Hello, world!</b>');
}
The code in the HtmlOutput can include embedded JavaScript and CSS. (This is standard client-side JavaScript that manipulates the DOM, not Apps Script). All of this content is sanitized using Google Caja, which applies some limitations to your client-side code. For more information, see the guide to restrictions in HTML service.
https://developers.google.com/apps-script/reference/html/html-output#

HTTP Parameter pollution attack

I developed a web application and deployed into the server and my security team come up with the below security remidiation issue.
Reflected HTML Parameter Pollution (HPP) is an injection weakness vulnerability that occurs when an attacker can inject a delimiter and change the parameters of a URL generated by an application. The consequences of the attack depend upon the functionality of the application, but may include accessing and potentially exploiting uncontrollable variables, conducting other attacks such as Cross-Site Request Forgery, or altering application behavior in an unintended manner. Recommendations include using strict validation inputs to ensure that the encoded parameter delimiter “%26” is handled properly by the server, and using URL encoding whenever user-supplied content is contained within links or other forms of output generated by the application.
Can any one have the idea about how to prevent HTML parameter pollution in asp.net
here is the script code in the webpage
<script type="text/javascript" language="javascript">
document.onclick = doNavigationCheck ;
var srNumberFinal="";
function OpenDetailsWindow(srNumber)
{
window.open("xxx.aspx?SRNumber="+srNumber+ "","","minimize=no,maximize=no,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,width=800,directories=no,resizable=yes,titlebar=no");
}
function OpenPrintWindow()
{
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
if(querystrActivityId != "")
{
var url = "abc.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + querystrActivityId + "";
}
else
{
var hdrActivityId = document.getElementById('<%=uxHdnHdrActivityId.ClientID%>').value;
var url = "PrintServiceRequestDetail.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + hdrActivityId + "";
}
childWinReference=window.open(url, "ChildWin","minimize=yes,maximize=yes,scrollbars=yes,status=yes,toolbar=no,menubar=yes,location=no,directories=no,resizable=yes,copyhistory=no");
childWinReference.focus();
}
function NavigateSRCopy(srNumber)
{
srNumberFinal = srNumber;
if (srNumber != "undefined" && srNumber != null && srNumber != "")
{
new Ajax.Request('<%= (Request.ApplicationPath != "/") ? Request.ApplicationPath : string.Empty %>/xxx/AutoCompleteService.asmx/CheckFormID'
, { method: 'post', postBody: 'srNumber=' + srNumber, onComplete: SearchResponse });
}
}
function SearchResponse(xmlResponse)
{
var xmlDoc;
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlResponse.responseText);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlResponse.responseText,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
if(xmlDoc.getElementsByTagName("string")[0].childNodes[0] != null)
{
formID = xmlDoc.getElementsByTagName("string")[0].childNodes[0].nodeValue;
}
else
{
formID = null;
}
if(formID != null && formID != "")
{
window.location.href = '/CustomerSupportRequest/CreateServiceRequest.aspx?id=' + formID + '&TemplateSR=' + srNumberFinal + '&Frompage=CopySR';
return true;
}
else
{
alert("This Service Request cannot be copied because it meets at least one of these conditions: \t\t\n\n * It was created prior to 10/15/2008 \n * It was auto generated as part of the Report Requeue Process \n * It was auto generated as part of the ERA Requeue Process \n * It was not created online");
}
}
function UpdateChildCases()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.show();
}
function HideParentChildPopup()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.hide();
return false;
}
function HideErrorSRNumsPopup()
{
var modalPopup = $find('modalParentErrorSRNumDisplay');
modalPopup.hide();
return false;
}
function HideRetrySRNumsPopup()
{
var modalPopup = $find('modalRetrySRNumDisplay');
modalPopup.hide();
return false;
}
function RemoveParent_ChildFlag(type)
{
var childCases = document.getElementById("<%=uxHdnChildCases.ClientID %>");
var msg = "";
var btn;
if(type == "Child")
{
if(childCases.value.indexOf(',') != -1)
msg = "Are you sure you want to remove the Child flag from this Service Request?";
else
msg = "This is the only child associated to the parent case. Removing the child flag will also remove the parent flag from the associated case. Choose OK to remove the flags, or Cancel to close this dialog";
btn = document.getElementById('<%=uxRemoveChildFlag.ClientID%>');
}
else
{
msg = "Removing the parent flag from this case will also remove the child flag from all associated cases. Are you sure you want to remove the Parent flag from this Service Request?";
btn = document.getElementById('<%=uxRemoveParentFlag.ClientID%>');
}
if(btn)
{
if(!confirm(msg))
{
return false;
}
else
{
btn.click();
}
}
}
function limitTextForParentChildComments()
{
var objLblCharCount = document.getElementById('uxLblPCCharCount');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if (objTxtComments.value.length > 1500)
{
objTxtComments.value = objTxtComments.value.substring(0, 1500);
}
else
{
objLblCharCount.innerHTML = 1500 - objTxtComments.value.length + " ";
}
setTimeout("limitTextForParentChildComments()",50);
}
function ValidateInputs()
{
var lblErrorMessage = document.getElementById('<%=lblCommentErrorTxt.ClientID%>');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if(objTxtComments.value.trim() == "")
{
lblErrorMessage.style.display = "block";
return false;
}
}
</script>
As per OWASP Testing for HTTP Parameter pollution, ASP.NET is not vulnerable to HPP because ASP.NET will return all occurrences of a query string value concatenated with a comma (e.g. color=red&color=blue gives color=red,blue).
See here for an example explanation.
That said, your code appears to be vulnerable to XSS instead:
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
If the query string parameter activityId="; alert('xss');" (URL encoded of course), then an alert box will trigger on your application because this code will be generated in your script tag.
var querystrActivityId = ""; alert('xss');"";

Context When Loading JS File Dynamically [duplicate]

I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!

Javascript Geolocation: Storing coordinates in an array

I created an HTML button:
...onclick="stLoc();"/>
which gears the stLoc() Javascript function.
My intention is to store the latitude inside the vaulesXarray.
Here's my code:
var valuesX=[];
//This is to show the current position:
function handleLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
valuesX.push(a);
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if (navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
The output I get is an empty array.
Your stLoc() function is expecting pos object to be passed as first parameter.
But in your HTML part of example you're not passing this parameter to function:
<a "onclick="stLoc();">
This causes the error and the application flow breaks.
Update:
button
<script type="text/javascript">
var valuesX=[],
lastPos={a: -1, b: -1};
//This is to show the current position:
function handleLoc(pos) {
// in event handler remember lastPos to use it in stLoc on click.
lastPos.a = pos.coords.latitude;
lastPos.b = pos.coords.longitude;
var p = new L.LatLng(lastPos.a, lastPos.b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc() {
if(lastPos.a != -1) {
valuesX.push(lastPos.a);
}
return false;
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if(navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
</script>
For guys looking out for code to implement this functionality in a different way..
Here is the code
<script language="javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript">
function geoSuccess(e){
var lat = e.coords.latitude;
var lon = e.coords.longitude;
var myLoc = "Latitude: " + lat + '<br />Longitude: ' + lon;
$("#mylocation").html(myLoc);
}
function geoFailed(e){
$("#mylocation").html("Failed");
}
window.onload=function(e){
if ( navigator.geolocation){
navigator.geolocation.getCurrentPosition(geoSuccess, geoFailed);
} else {
// Error (Could not get location)
$("#mylocation").html("Failed");
}
}
</script>
<div id="mylocation"></div>

Categories

Resources