I am having issues passing two coordinates from one function to another. I don't really know JavaScript, but it seems to be somewhat correct. Could you please let me know where is my error?
<head>
<script>
var zoom = 12; // 18 for mobile phones because the geolocation is more accurate
function init() {
// Don't bother if the web browser doesn't support cross-document messaging
if (window.postMessage) {
if (navigator && navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(pPos) {
send(pPos.coords.latitude, pPos.coords.longitude);
}, function() {});
} catch (e) {}
} else if (google && google.gears) {
// Relevant if targeting mobile phones (some of which may have Google Gears)
try {
var geoloc = google.gears.factory.create("beta.geolocation");
geoloc.getCurrentPosition(function(pPos) {
send(pPos.latitude, pPos.longitude);
}, function() {});
} catch (e) {}
}
}
}
function send(pLat, pLng) {
var myiframe = document.getElementById("myiframe").contentWindow;
// The third parameter, zoom, is optional
myiframe.postMessage(pLat + "," + pLng + "," + zoom, "http://www.qib.la");
}
window.onload=init;
</script>
</head>
<body>
<iframe id="myiframe" src="http://www.qib.la/embed/" width="400" height="400">
Check the prayer direction towards the Ka'ba in Makkah at
Qibla Direction.
</iframe>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<br>
<p align="center">Waterloo, ON, Canada<p>
<div align="center" id="table"></div>
<script type="text/javascript">
var date = new Date(); // today
var times = prayTimes.getTimes(date, pLat + "," + pLng, -5);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
</script>
</body>
Is it possible to return a value from an asynchronous function? How do I use a callback here?
You have a syntax error in this code:
var times = prayTimes.getTimes(date, + b + ',' + c + , -5);
You have a "+" and then a comma immediately following it. I'm not sure what your intent for the code was, but that is what is causing it to not run.
Perhaps you intended to follow the pattern of appending the commas as strings?
var times = prayTimes.getTimes(date + ',' + b + ',' + c + ',' + -5);
Or perhaps that -5 was meant to be a separate argument?
var times = prayTimes.getTimes(date, b + ',' + c, -5);
Related
I have written the code below but now I have to write this with jQuery because of security reasons. I have never done something with jQuery before and I really don't know, how to write this.
I shouldn't mix the HTML with JS and should use createElement and stuff like that.
var demoName1 = "Peter Stone";
function showMessage() {
var newMsg = '<div id="messageBoxSend">' +
'<div class="nameSend">' + demoName1 + '</div>' +
'<div class="text">' +
' <div id="FscToolPaneNoseSend">' +
'</div></div>' +
document.getElementById('inputText').value;
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
if (c < 10) {
c = "0" + c;
}
var time = b + ':' + c;
newMsg += '<div class="time">' + time + '</div>' +
' </div></div><br>';
...
}
You will try this code
$('class or id').html('');
$('class or id').html(newMsg);
jQuery is a library for JavaScript, so yes, if you consider JavaScript to be insecure, then jQuery is, as well. Also, jQuery makes AJAX easier, but it doesn't prove that Jquery is secure than javascript.
It would be something like the below. You should probably look into the jQuery docs https://jquery.com/
var demoName1 = "Peter Stone";
function showMessage() {
var input = $('#inputText').val();
$('.nameSend').html(demoName1 + input);
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
if (c < 10) {
c = "0" + c;
}
var time = b + ':' + c;
$('#messageBoxSend').append(time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inputText">
<div id="messageBoxSend">
<div class="nameSend"></div>
</div>
<div class=""></div>
<button onclick="showMessage();">Click me!</button>
After reading the comments and your question, I realized that the security concern should be answered. It is recommended to sanitize the HTML before using innerHTML().
You can read more on creating DOM elements and using innerHTML() safely here https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page
I was given this task with some existing code to change the string color of each of three selector.value(s) that is output onto an input element to three different colors. The code boils the three selectors into a single output variable. Without destroying the code, I cannot figure out how to select each individual variables prior to condensing them.
If I could use the fontcolor() method, my life would be great but it's 2018 and I can't. Is there any way you can think of to solve this issue?To clarify, I need to alter the colors of the strings that belong to output(red), select1.value(blue) and select2.value(black.
Most of the action for this is happening in the parseOutput() function but I'm just stuck and don't think it's possible without rewriting the entire program.
function updateSelector(result){
var options = result.options;
var elementId = "select" + result.element;
var logger = document.getElementById('logger');
var selector = document.getElementById(elementId);
//logger.innerHTML = JSON.stringify(elementId);
selector.innerHTML = options;
selector.disabled = false;
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
plate();
function resetAll(){
for (var i = 0;i<3;i++){
var selector = document.getElementById('select' + i);
selector.disabled = true;
selector.innerHTML = "";
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
}
function finalSelection(){
var output = document.getElementById('out');
//output.focus();
output.select();
}
function plate(){
var plate = document.getElementById('plate');
plate.innerHTML = atob('Q3JhZnRlZCBieTogWmFjaGFyeSBTdGFjaG93aWFr');
}
//Adds the location as initial output, followed by divider, application, and issue if select1 is selected
//else statement added so if select0 is [Costco Website Name], to ommit the " - "
function parseOutput(){
var output = "";
if (select1.value.length > 0 && select0.value !== "[Costco Website Name]"){
output = output + ' - ' + select1.value + ' // ' + select2.value;
} else{
output = output + select1.value + ' // ' + select2.value;
}
out.value=output.trim();
}
And this is the Div that displays the output:
<div class="wide"><p><input class="wide" type="readonly" id="out" onfocus="this.select();"></p></div>
A modern replacement for fontcolor would use a span and a style (or class), e.g.:
function modernFontColor(str, color) {
return '<span style="color: ' + color + '">' + str + '</span>';
}
or
function modernFontClass(str, cls) {
return '<span class="' + cls + '">' + str + '</span>';
}
...where the class defines the styling.
If I include a script with an external source and then try to parse using jQuery - it will download the script, but won't load it into the DOM. I'm using using .append(), but this seems to be the case for any other jQuery DOM insertion method.
Here's an example in Stack Snippets
$(function(){
var selet2Html =
'<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
'<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
'<select class="select2">' +
' <option value="AK">Alaska</option>' +
' <option value="HI">Hawaii</option>' +
'</select>' +
'<script >' +
' $(function() {' +
' $(".select2").select2();' +
' });' +
'<\/script>';
$("body").append(selet2Html);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
Even though this will download the script in the network tab:
It will still return the following error (indicating that the external library - select2 - never loaded):
I'd prefer not to use $.getScript() as I'm actually loading this string dynamically with .load(), so I'm not sure if it's going to contain any external scripts or not.
How can I get it to load the external library?
So dandavis is right - the library needs time to load before calling the initializer on it. A naive implementation could just wait a short amount of time and try again like this:
setTimeout( function() {
$(".select2").select2();
}, 2000);
Simple Demo in Stack Snippets:
$(function(){
var selet2Html =
'<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
'<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
'<select class="select2">' +
' <option value="AK">Alaska</option>' +
' <option value="HI">Hawaii</option>' +
'</select>' +
'<script >' +
' setTimeout( function() {' +
' $(".select2").select2();' +
' }, 2000);' +
'<\/script>';
$("body").append(selet2Html);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
A more sophisticated solution would wait until $.fn.select2 showed up in the DOM.
Enter OnAvailable
You can call it like this:
onAvailable('$.fn.select2', function() {
alert('we did it');
});
Here's the function that will poll the global namespace for your variable to popup. It uses Alnitak's Object.byString solution from Accessing nested JavaScript objects with string key
function onAvailable(listenFor, callback) {
var interval = window.setInterval(function() {
if (Object.byString(window, listenFor)) {
clearInterval(interval);
callback()
}
}, 100);
};
Advanced Demo in Stack Snippets
function onAvailable(listenFor, callback) {
var interval = window.setInterval(function() {
if (objectFromString(window, listenFor)) {
clearInterval(interval);
callback()
}
}, 100);
};
function objectFromString(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
$(function(){
var selet2Html =
'<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
'<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
'<select class="select2">' +
' <option value="AK">Alaska</option>' +
' <option value="HI">Hawaii</option>' +
'</select>' +
'<script >' +
' onAvailable("$.fn.select2", function() {' +
' $(".select2").select2();' +
' });' +
'<\/script>';
$("body").append(selet2Html);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
I have a question with my JavaScript code (I am quite new at this...). I am making a test where I will calculate the score of the participants by using their answers. I have multiple variables where I store these answers. And also the calculation of the score is going ok. Then I have a table with the scores. That is like this:
<script type="text/javascript">
var row1col1var="Fruit";
var rowicol2var="% of how much I love them";
var applep=34; //result from score calcultaion
var row2col1var="Apple";
var bananasp=65; //result from score calcultaion
var row3col1var="Bananas";
document.write('<center><table width="50%" border="0">');
document.write('<tr align="center"><td>' + row1col1var + '<\/td><td>' + rowicol2var + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row2col1var + '<\/td><td' + applep + "%" + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row3col1var + '<\/td><td' + bananasp + "%" +'<\/td><\/tr>');
document.write('<\/table><\/center>'); </script>
Here I display the results per "fruit" in a table. What I cannot get to work is this:
I want to pick out the best score (in this case 65, for Bananas) and display: "You love Bananas the most." (ie link 65 to Bananas and display Bananas). I was trying to give the cells an id with the name Apples or Bananas and calling on the id to display it, but this did not work.
My problem breaks down in two pieces:
1. I cannot get math.max to work on variables.
2. I do not know how to link the highest score to its "name" (ie 65 belongs to Bananas).
I hope you can help me!!
You need to use more appropriate way for coding. For storing data, you can use object or array. I am using an array for this example.
Check this :
<html>
<head>
<script type="text/javascript">
function getScore(){
var scoreArr = [];
scoreArr.push(['apple', '35']);
scoreArr.push(['apple', '65']);
var maxPercentage = null;
var lovedFruit = '';
var finalScore = '<center><table width="50%" border="0"><tr align="center"><th>Fruits</th><th>% of how much I love them</th></tr>';
for (var i = 0; i < scoreArr.length; i++) {
finalScore += '<tr align="center"><td>' + scoreArr[i][0] + '</td><td>' + scoreArr[i][1] + "%" + '</td></tr>';
if (maxPercentage === null) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
} else {
if (maxPercentage < parseInt(scoreArr[i][1])) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
}
}
}
finalScore += '</table><br>Result is : ' + maxPercentage + ' belongs to ' + lovedFruit + '</center>';
// WITH JAVASCRIPT
var container = document.createElement('div');
container.innerHTML = finalScore;
document.body.insertBefore(container, null); //append div to end
// WITH JQUERY
// $('body').append(finalScore);
}
</script>
</head>
<body onLoad=getScore()>
</body>
</html>
It will store your data in array and then you can do whatever you want in more sophisticated way.
I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.