I have been playing with JavaScript and Arduino Ethernet Shield for a while and I am trying to send data from Arduino to the webpage it serves using AJAX. The data I send is an array of 24 variables. In order to display the data I created a table in JavaScript using the for() loop. The problem is that when I try to assign the variables to the table cells (one variable per cell), only the first cell of the table receives data. The thing is that when I create the table using HTML (all cells created with the <td></td> tags), the variables are assigned to the table cells properly. Thank you for your time!
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Arduino WebBased Weather Station</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<style>
#charset 'UTF-8';#import url(https://fonts.googleapis.com/css?family=Open+Sans:300,400,700);
body {
background-color: black;
font-family: 'Open Sans', sans-serif;
line-height: 1em;
text-align: center;
Color: #cccccc;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
margin-left:auto;
margin-right:auto;
}
th {
border: 1px solid #336699;
color:#0040ff;
text-align: center;
padding: 8px;
}
td {
border: 1px solid #336699;
color:#0080ff;
text-align: center;
padding: 8px;
}
td.td2 {
border: 1px solid #336699;
color:#0080ff;
text-align: left;
padding: 8px;
}
</style>
<h1>Arduino Web-Based Weather Station</h1><hr>
<h3>WELCOME!</h3>
<p>Project is hosted on github. Please visit my <a href='https://github.com/zissis-pap'>page</a> for more!</p><hr>
</head>
<body onload="BuiltArray(); GetArduinoIO()"><br>
<div id="array1"></div>
<script>
var bool = false;
function BuiltArray() {
var arr1 ="<table style='width:100%'><tr><th colspan='25'>\
AVERAGE CONDITIONS FOR THE LAST 24 HOURS</th></tr><tr><td\ class='td2'>HOURS:</td>"
for (var i = 0; i <= 23; i++) {
arr1 += "<td><font color='#3d0099'>\
<span class='hrs'>...</span></font></td>";
}
arr1 += "</tr></table>";
document.getElementById("array1").innerHTML = arr1;
bool = true;
}
function GetArduinoIO() {
if(bool == true) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
// XML file received - contains analog values, switch values and LED states
var count;
// get analog inputs
var num_an = this.responseXML.getElementsByTagName('hours').length;
for (count = 0; count < num_an; count++) {
document.getElementsByClassName("hrs")[count].innerHTML =
this.responseXML.getElementsByTagName('hours')[count].childNodes[0].nodeValue;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs", true);
request.send();
setTimeout('GetArduinoIO()', 2000);
}
}
</script>
</body>
</html>
Related
I'm working on a portfolio project - which should use jquery - part of the task is to set and get text via localstorage - which I can do in Javascript but I breaks when attempting to refactor in jquery.
I found an elegantly simple javascript codepen, which has all the features I want. But when I refactor into jquery it loses funtionality - I can't save the text to local storage (I get null) and I can't copy the text to a different Div.
This is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Local Test</title>
</head>
<body>
<div class="content-output"></div>
<textarea class="content-input" placeholder="Your text here"></textarea>
<button class="save-button">Save</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./script.js"></script>
</body>
</html>
This is simple CSS from the JS code pen:
* {
font-size: 16px;
font-family: sans-serif;
}
body {
padding: 1rem;
font-family: sans-serif;
}
.content-output {
float: left;
box-sizing: border-box;
background: #f9f9f9;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
color: #202020;
}
.content-input {
float: left;
box-sizing: border-box;
margin-left: 2rem;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
border: 1px solid #505050;
resize: none;
}
.save-button {
/* -webkit-appearance: none; */
border: 0;
background: #0088ff;
padding: 0.5rem 1rem;
border-radius: 3px;
color: #fff;
margin-top: 1rem;
float: right;
cursor: pointer;
}
Here is the JS which works:
var input_textarea = document.querySelector(".content-input");
var output_div = document.querySelector(".content-output");
var save_button = document.querySelector(".save-button");
save_button.addEventListener("click", updateOutput);
output = localStorage.getItem("content");
input = localStorage.getItem("content");
console.log(output);
output_div.textContent = output;
function updateOutput() {
console.log("clicked button");
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
And here is the jquery which doesn't work:
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
I'm running out of ideas and searches - probably a typo but I cant find it . I've tried text() which was the advice 6 years ago. JSON.stringify and parse don't help because it's just a string.
I'm hoping someone has done some refactoring and spots the differences - I've even run this in the console but I can only add the text to localstorage manually: localstorage.setItem('content', 'help')
Thanks in advance
The problem is that you are trying to select a array, get the value of that array, and output to another array. I think jquery does that when you select a class, (because there could be more than one of them). Simple solution to this..
var input_textarea = $(".content-input")[0];
console.log(input_textarea)
var output_div = $(".content-output")[0];
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
console.log('hello')
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
Found it: val() to set and text() to get.
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
// input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.val());
output_div.text(localStorage.getItem("content"));
}
this post helped: How to save the value of textarea to localstorage then display it in the same textarea
I'm learning JavaScript, and decided to try out a simple guessing game thing. The code I have at the moment:
The HTML:
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="guessing_game.css">
</head>
<body>
<h1>Welcome to the guessing game</h1>
<p>You have to guess the number within 5 attempts, so good luck!</p>
<p>Enter a number:</p>
<input type="text" id="number" placeholder="Enter number"></br>
<input type="submit" id="submit" value="Guess!"></br>
<aside>
<div id="counter">
<p>Remaining Guesses</p>
</div>
<p id="remaining"></p>
</aside>
<div id="result"></div>
<script type="text/javascript" src="guessing_game.js"></script>
</body>
</html>
The JS:
var guesses = 5;
function guess() {
var elGuess = document.getElementById("remaining");
var elResult = document.getElementById("result");
/* if(guesses === 0) {
elResult.innerHTML = "<p>Sorry, you ran out of guesses! Better
luck next time.</p>";
return;
}*/
if(guesses > 0) {
guesses--;
elGuess.textContent = guesses;
//random number
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if(userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
else {
elResult.textContent = "Sorry, please try again.";
}
}
else {
elResult.textContent = "Sorry, you ran out of guesses.";
}
}
var elSubmit = document.getElementById("submit");
elSubmit.addEventListener("click", guess, false);
and the CSS:
body {
font-family: 'Roboto', sans-serif;
}
aside {
position: relative;
top: -150px;
width: 300px;
height: 600px;
float: right;
border-left: 2px solid gray;
}
#counter p{
position: absolute;
top: 120px;
width: 140px;
left: 60px;
border-top: 2px solid brown;
text-align: center;
border-bottom: 2px solid brown;
padding: 5px;
}
#remaining {
font-size: 220%;
text-align: center;
font-family: Arial, Verdana, serif;
position: absolute;
top: 170px;
border-bottom: 1px solid green;
padding: 2px;
left: 130px;
color: #ff2400;
}
#result {
font-family: 'Open Sans', sans-serif;
text-align: center;
font-size: 1.2em;
letter-spacing: 0.9em;
color: gray;
}
What I was looking to do was - as soon as the number of guesses reach 0, the result should display that you're out of guesses. I've managed to validate the guesses counting down to 0 (not going to negative). I tried using an if statement which would check if the guesses were out, then set the result accordingly and return. But apparently, as soon as return is reached, the control exits the method. I didn't know this would happen even inside an if that's never reached.
Either way, how do I modify the code such that the result is set as soon as the guesses left hit zero?
Remember that your variable guesses might not be what is displaying on the remaining element, you should decrement the variable before your condition.
var guesses = 5;
function guess() {
var elGuess = document.getElementById("remaining");
var elResult = document.getElementById("result");
if (guesses===0){
return;
}
guesses--;
elGuess.textContent = guesses;
if(guesses > 0) {
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if(userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
else {
elResult.textContent = "Sorry, please try again.";
}
}
else {
elResult.textContent = "Sorry, you ran out of guesses.";
}
}
var elSubmit = document.getElementById("submit");
elSubmit.addEventListener("click", guess, false);
Since you're decrementing your guesses counter inside that if statement, you need to move your check for guesses === 0 inside of that same block somewhere below guesses--;
if (guesses > 0) {
guesses--;
elGuess.textContent = guesses;
//random number
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if (userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
if (guesses === 0) {
elResult.textContent = "Sorry, you ran out of guesses."
} else {
elResult.textContent = "Sorry, please try again.";
}
}
Also, next time you post a question like this consider also linking to a free online sandbox like CodePen or JSBin. That way people can edit your code without having to copy/paste.
Here's the CodePen I made for your question:
http://codepen.io/ultralame/pen/OyWbeW.js
<script>
$(document).ready(function(){
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};
//select row on which conditional formatting will apply
$(".conditional").each(function(){
// get all TDs except for first column
var counts= $(this).find(':nth-child(n+1)');
// return max value
var max = Array.max(counts);
xr = 255;
xg = 255;
xb = 255;
yr = 243;
yg = 32;
yb = 117;
n = 100;
// Iterates on each TD except the first column
$(this).find(':nth-child(n+1)').each(function(){
//assign color based on difference from min and max
var val = parseInt($(this).text());
var pos = parseInt((Math.round((val/max)*100)).toFixed(0));
red = parseInt((xr + (( pos * (yr - xr)) / (n-1))).toFixed(0));
green = parseInt((xg + (( pos * (yg - xg)) / (n-1))).toFixed(0));
blue = parseInt((xb + (( pos * (yb - xb)) / (n-1))).toFixed(0));
clr = 'rgb('+red+','+green+','+blue+')';
$(this).css("background-color",clr);
});
});
});
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
.year {
background-color: #eeeeee;
font-size: 30px;
text-align: center;
font-weight: bold;
padding: 30px;
}
table.tableizer-table {
border: 1px solid #CCC; font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
margin:auto
}
.tableizer-table td {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
text-align: center;
width:120px;
}
.tableizer-table th {
background-color: #eeeeee;
color: #111;
font-weight: bold;
padding: 10px;
font-size: 18px;
}
.separator {
background-color: #ffffff;
}
.firstcolumn {
font-weight: bold;
}
</style>
</head>
<body>
<table id="mytable" class="tableizer-table">
<tr><td class="year">2015</td></tr>
<tr class="conditional"><td class="firstcolumn">Hwy (MPGe)</td><td>109</td><td>108</td><td>110</td><td>92</td><td>101</td><td>93</td><td> </td></tr>
<tr class="conditional"><td class="firstcolumn">City (MPGe)</td><td>128</td><td>122</td><td>99</td><td>120</td><td>126</td><td>122</td><td> </td></tr>
<tr class="conditional"><td class="firstcolumn">Combined (MPGe)</td><td>119</td><td> </td><td>105</td><td>105</td><td>114</td><td>114</td><td> </td></tr>
</table>
I am new to Jquery and javascript and trying to implement conditional formatting on a html table. Where the numbers in one row are compared and the lowest element will have a white background and the highest number will have a green background.
The rows on which the conditional formatting needs to work have a class called "conditional". The first column does not contain a number so needs to be excluded from the conditional formatting.
I have been spending several days to do this and cannot succeed.
I found the following piece of code and modified it slightly for my specific needs but it does not work.
I ran it in a browser called from this HTML document:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src='~/altitude/jquery-2.1.4.min.js'></script>
<script type="text/javascript" src="~/workspace/test.js";></script>
</head>
<body>
<ul id = "squarePos">
<li class = "conditional">Header</div>
<li class = "conditional">1</div>
<li class = "conditional">4</div>
<li class = "conditional">2</div>
<li class = "conditional">3</div>
</ul>
</body>
</html>
The code won't run because you seem to have more than one set of unmatching parenthesis or brackets.
If you use firefox (which I do for web developement) you can hit Ctrl-Shift-K to get a web console that will show you where you have syntax errors in your javascript so you can get on to the debugging.
i read a value from a XML file using ajax jquery and make it appear on the browser the problem is when i change the value of my xml file i can't figure out how to make it change automatically in the browser
the xml (counter.xml) file:
<?xml version="1.0"?>
<count><number>5</number></count>
the php (slideshow.php):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
body { font-family: Helvetica, Arial, sans-serif; line-height: 1.3em; -webkit-font-smoothing: antialiased; }
.container {
width: 90%;
margin: 20px auto;
background-color: #FFF;
padding: 20px;
}
pre, code {
font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
font-size: 12px;
color: #333;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
pre { border: 1px solid #CCC; background-color: #EEE; color: #333; padding: 10px; overflow: scroll; }
code { padding: 2px 4px; background-color: #F7F7F9; border: 1px solid #E1E1E8; color: #D14; }
</style>
</head>
<body>
<div id="result">
<script type="text/javascript">
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
var mygetrequest=new ajaxRequest()
if (mygetrequest.overrideMimeType)
mygetrequest.overrideMimeType('text/xml')
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
var xmldata=mygetrequest.responseXML //retrieve result as an XML object
var rssentries=xmldata.getElementsByTagName('Count')
var output='<ul>'
for (var i=0; i<rssentries.length; i++){
output+='<li>'
output+='<a href="'+rssentries[i].getElementsByTagName('Number')[0].firstChild.nodeValue+'">'
output+=rssentries[i].getElementsByTagName('Number')[0].firstChild.nodeValue+'</a>'
output+='</li>'
}
output+='</ul>'
document.getElementById("result").innerHTML=output
}
else{
alert("An error has occured making the request")
}
}
}
mygetrequest.open("GET", "counter.xml", true);
mygetrequest.send(null);
</script>
<script type="text/javascript">
refreshdiv();
</script>
</div>
</body>
<script src="../libs/jquery/jquery.js"></script>
<script src="../src/jquery.backstretch.js"></script>
<script>
$.backstretch([
<?php
$directory = "images/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.j*");
//print each file name
$output="";
//$nbrImages= 0;
foreach($images as $image)
{
$output.="'".$image."',";
//$nbrImages = $nbrImages + 1;
}
echo substr_replace($output,"",-1);
?>
], {
fade: 750,
duration: 4000
});
</script>
</body>
</html>
try this one
setTimeout(function(){
//your ajax code
},100);
You would need something like this
setInterval(
function(){
//your ajax call
}
,100 //The time in milliseconds that should repeat the ajax call
);
the setInterval function sets a logic that will repeat the given task in the timing you set. So you could check and load the .xml file every x seconds.
You can stop the repeat like this
var interval = setInterval(function(){ //your function }, 100);
clearInterval(interval);
Other then from #pratik nagariya mentioned the
setTimout()
function will only delay your call, but not repeat it.
I just did some quick searches and found that you could use this code:
reloadinterval=window.setInterval(function(){
old=rssentries;
// your ajax reqest code
if(!(rssentries==old)){window.reload();}
}, 3000 //the time interval in milliseconds);
In my stop watch history table , it shows history of start time, end time, length, time between.
But if I refresh browser then previous value gone . I need previous data will remain for next time , data will store in local storage.
Thanks for any help.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
function PadDigits(n, totalDigits)
{
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (i=0; i < (totalDigits-n.length); i++)
{
pd += '0';
}
}
return pd + n.toString();
}
var lastEndTime = null;
var starttime = null;
var endtime = null;
function startTimer()
{
date = new Date();
starttime = date;
if(lastEndTime == null)
{
$('#history').html('');
}
$('#action').html('<img src="pause.png"><br>Stop Timer');
}
function stopTimer()
{
$('#action').html('<img src="play.png"><br>Start Timer');
date = new Date();
endtime = date;
addRowToTable(starttime,endtime,lastEndTime);
lastEndTime = endtime;
endtime = null;
starttime = null;
}
function addRowToTable(starttime,endtime,lastEndTime)
{
formattedStart = PadDigits(starttime.getHours(),2)+':'+PadDigits(starttime.getMinutes(),2)+":"+PadDigits(starttime.getSeconds(),2);
formattedEnd = PadDigits(endtime.getHours(),2)+':'+PadDigits(endtime.getMinutes(),2)+":"+PadDigits(endtime.getSeconds(),2);
seconds = parseInt((endtime.getTime() - starttime.getTime())/1000);
lengthMinutes = parseInt(seconds/60);
lengthSeconds = parseInt(seconds%60);
lengthFormatted = PadDigits(lengthMinutes,2)+":"+PadDigits(lengthSeconds,2);
if(lastEndTime == null)
{
timeBetweenFormatted = "N/A";
}
else
{
timeBetween = parseInt((starttime.getTime() - lastEndTime.getTime())/1000);
timeBetweenMinutes = parseInt(timeBetween/60);
timeBetweenSeconds = parseInt(timeBetween%60);
timeBetweenFormatted = PadDigits(timeBetweenMinutes,2)+":"+PadDigits(timeBetweenSeconds,2);
}
$('#history').prepend('<tr><td>'+formattedStart+'</td><td>'+formattedEnd+'</td><td>'+lengthFormatted+'</td><td>'+timeBetweenFormatted+'</td></tr>')
}
function toggleTimer()
{
if (starttime == null)
{
startTimer();
}
else
{
stopTimer();
}
}
$(document).ready(function(){
$('#action').click(function(kevent){
toggleTimer();
});
$(document).keypress(function(kevent){
$('#action').click();
});
});
</script>
<style type="text/css">
body, body *{
font-family: Helvetica;
}
body{
margin:0px;
}
table.data-table
{
width: 100%;
background-color: #FFFFFF;
font-size: 11px ;
border: 0px;
border-collapse: collapse;
border-top: 1px solid #000000;
border-bottom: 1px solid #000000;
}
table.data-table thead
{
border-top: 1px solid #000000;
border-bottom: 1px solid #000000;
}
table.data-table thead th
{
background: #DDDDDD url(data-table-header.png) repeat-x top;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(248, 248, 248)), color-stop(0.5, rgb(248, 248, 248)), color-stop(0.5, rgb(233, 233, 233)), to(rgb(233, 233, 233))) content-box padding-box;
text-align: left;
padding-left: 2px;
}
table.data-table tr:nth-child(2n)
{
background-color: #ECF3FE;
}
table.data-table tr:odd
{
background-color: #ECF3FE;
}
table.data-table td
{
padding-left: 2px;
}
table.data-table tbody
{
overflow-y: auto;
}
#action
{
border: 0px;
background: transparent;
}
</style>
</head>
<body>
<button type="button" id="action"><img src="play.png"><br>Start Timer</button><br>
<div>
<table class="data-table">
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
<th>Length</th>
<th>Time Between</th>
</tr>
</thead>
<tbody id="history">
</tbody>
</table>
</div>
</body>
</html>
you can use cookies which will be the easiest and simplest solution
check this
http://www.w3schools.com/js/js_cookies.asp
If you have to store all the previous values in a local storage you can store array of objects in to a local storage variable and than access it on page load.
The objective is to store the data into local storage once a lap is completed. And on browser refresh it has to check for stored laps, if any are stored it has to update them on html before proceeding. This will help you to achieve it.
var rows = new Array();
var lastEndTime = null;
var starttime = null;
var endtime = null;
function stopTimer()
{
// Your code
addRowToTable(starttime,endtime,lastEndTime);
addRowToLocalStorage(starttime,endtime,lastEndTime);
}
// This will update your local storage data with all time laps
function addRowToLocalStorage(starttime, endtime, lastendtime)
{
var row = {
'startTime' : starttime,
'endtime' : endtime,
'lastendtime' : lastendtime
};
rows.push(row);
localStorage.setItem("savedData", JSON.stringify(rows));
}
// Onpage load, update all your local storage data to html
$(function(){
var historyLaps = JSON.parse(localStorage.getItem("savedData"));
$.each(historyLaps, function(lap) {
addRowToTable(lap.starttime, lap.endtime, lap.lastEndTime);
});
});
// Deletes the local data. You can keep a rest button in html and tie it to this.
function clearStorage(){
localStorage.removeItem('savedData');
}
This is untested code and probably might not work as expected. But, this will get you started. I hope this will help you.