Problem with binding JavaScript data.

Diskutiere Problem with binding JavaScript data. im HTML Forum im Bereich Programmierung; when ever i try to bind my javaScript code to my html code content from my page is missing that happing when i bind my javaScript cod in the top...
U

user12

Member
Dabei seit
05.08.2021
Beiträge
5
when ever i try to bind my javaScript code to my html code content from my page is missing that happing when i bind my javaScript cod in the top of my html code , but if i bind it on the bottom before the 2 line of my html code i get no error and every things works just fine, but i dont want that bc it is bad practice! can anyone tell me where is the problem, and why binding my html code in the top is probmle which what should be the right way to do it.



<!DOCTYPE html>
<html>
<!-- Rui Santos - Complete project details at https://RandomNerdTutorials.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. -->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://code.highcharts.com/highcharts.js"></script>
<script type='text/javascript' src="app.js"></script>


<link rel="stylesheet" href="style.css" />
</head>

<body onload="set_ButtonState()">
<div class="div__p__motor"> Motor Status</div>
<div class="motor_pos__div">
<div class="motor__div">
<h3>Aus / AN <span id="outputState"></span></h3>
<label class="switch">
<input type="checkbox" name="motor_on_off" onchange="toggleCheckbox(this)" id="motor_on_off" " +
outputStateValue + ">
<span class="slider"></span>
</label>
</div>
<div class="interval__div">
<h3>Interval <span id="outputState"></span></h3>
<label class="switch">
<input type="checkbox" name="motor_mix" onchange="toggleCheckbox(this)" id="motor_interval" " +
outputStateValue + ">
<span class="slider"> </span>
</label>
</div>
<div class="mix__div">
<h3>Mix<span id="outputState"></span></h3>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)" id="motor_mix" " +
outputStateValue + ">
<span class="slider"> </span>
</label>
</div>
</div>
<div class="temp__sttings">
<input
class="temp__slider"
type="range"
id="myRange"
value="20"
onchange="myFunction(this.value)"
/>
<div class="temperature__p"> Motor = </div>
<div class="temp__slider__p" id="demo"> 1</p></div>

</div>
<div class="div__p__temprature">Temprature</div>
<div class="temp__div">
<div class="mix__div">
<h3>AN/AUS<span id="outputState"></span></h3>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)" id="output_temp" " +
outputStateValue + ">
<span class="slider"> </span>
</label>
</div>
</div>
<div class="temp__sttings">
<input
class="temp__slider"
type="range"
id="myRange2"
value="20"
onchange="myFunction2(this.value)"
/>
<div class="temperature__p"> &#8451; </div>
<div class="temp__slider__p" id="demo2"> 1</p></div>
</div>
<!--- Diagramm-->
<div id="chart-temperature" class="container"></div>
<div id="chart-Motor" class="container"></div>
<!-- <div id="chart-pressure" class="container"></div> -->

</body>
</html>
 
basti1012

basti1012

Well-known member
Dabei seit
12.06.2018
Beiträge
138
my english is very shit.
Show me the content of app.js.
Then I'll show you what the problem is,
with my English I can never explain it

about as:
inline function calls must be removed and addEventListener should be used.
The JS code should then be in a domContentloadet event
 
U

user12

Member
Dabei seit
05.08.2021
Beiträge
5
here is my app.js




function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
//if(element.id=="motor_on_off"){
console.log(element.id);
if(document.getElementById(element.id).checked == true)
xhr.open("GET", "/update?button=" + element.id + "&motor_on_off=1&motor_interval=2&motor_mix=3", true);

else
xhr.open("GET", "/update?motor_on_off=4&motor_interval=5&motor_mix=6", true);
//}
xhr.send();
}
function set_ButtonState() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
alert(this.responseText);
if (this.responseText == "1") {
document.getElementById("motor_on_off").checked = true;
} else if (this.responseText == "0") {
document.getElementById("motor_on_off").checked = false;
}
}
};
xhttp.open("GET", "get_MotorState", true);
xhttp.send();
}


var chartT = new Highcharts.Chart({
chart: { renderTo: "chart-temperature" },
title: { text: "BME280 Temperature" },
series: [
{
showInLegend: false,
data: [],
},
],
plotOptions: {
line: {
animation: false,
dataLabels: { enabled: true },
},
series: { color: "#059e8a" },
},
xAxis: {
type: "datetime",
dateTimeLabelFormats: { second: "%H:%M:%S" },
},
yAxis: {
title: { text: "Temperature (Celsius)" },
//title: { text: 'Temperature (Fahrenheit)' }
},
credits: { enabled: false },
});
setInterval(function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var x = new Date().getTime(),
y = parseFloat(this.responseText);
//console.log(this.responseText);
if (chartT.series[0].data.length > 40) {
chartT.series[0].addPoint([x, y], true, true, true);
} else {
chartT.series[0].addPoint([x, y], true, false, true);
}
}
};
xhttp.open("GET", "/temperature", true);
xhttp.send();
}, 10000);
var chartH = new Highcharts.Chart({
chart: { renderTo: "chart-Motor" },
title: { text: "Motor" },
series: [
{
showInLegend: false,
data: [],
},
],
plotOptions: {
line: { animation: false, dataLabels: { enabled: true } },
},
xAxis: {
type: "datetime",
dateTimeLabelFormats: { second: "%H:%M:%S" },
},
yAxis: {
title: { text: "Humidity (%)" },
},
credits: { enabled: false },
});
setInterval(function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var x = new Date().getTime(),
y = parseFloat(this.responseText);
//console.log(this.responseText);
if (chartH.series[0].data.length > 40) {
chartH.series[0].addPoint([x, y], true, true, true);
} else {
chartH.series[0].addPoint([x, y], true, false, true);
}
}
};
xhttp.open("GET", "/humidity", true);
xhttp.send();
}, 10000);
function myFunction() {
var x = document.getElementById("myRange").value;
document.getElementById("demo").innerHTML = x;
}
function myFunction2() {
var x = document.getElementById("myRange2").value;
document.getElementById("demo2").innerHTML = x;
}
 
basti1012

basti1012

Well-known member
Dabei seit
12.06.2018
Beiträge
138
can you test that first.
in the app.js. Insert in the first line
Javascript:
document.addEventListener ("DOMContentLoaded", function (event) {

in the last line
Javascript:
})
If that's not enough, I have to change something else

please check your console to see which errors are displayed
 
U

user12

Member
Dabei seit
05.08.2021
Beiträge
5
Did it like this:
Javascript:
document.addEventListener ("DOMContentLoaded", function (event) {
    var xhr = new XMLHttpRequest();
    //if(element.id=="motor_on_off"){
        console.log(element.id);
        if(document.getElementById(element.id).checked == true)
            xhr.open("GET", "/update?button=" + element.id + "&motor_on_off=1&motor_interval=2&motor_mix=3", true);
        
        else
            xhr.open("GET", "/update?motor_on_off=4&motor_interval=5&motor_mix=6", true);
    //}
    xhr.send();
  }

  function set_ButtonState() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        // Typical action to be performed when the document is ready:
        alert(this.responseText);
        if (this.responseText == "1") {
          document.getElementById("motor_on_off").checked = true;
        } else if (this.responseText == "0") {
          document.getElementById("motor_on_off").checked = false;
        }
      }
    };
    xhttp.open("GET", "get_MotorState", true);
    xhttp.send();
  }
 
 
  var chartT = new Highcharts.Chart({
    chart: { renderTo: "chart-temperature" },
    title: { text: "BME280 Temperature" },
    series: [
      {
        showInLegend: false,
        data: [],
      },
    ],
    plotOptions: {
      line: {
        animation: false,
        dataLabels: { enabled: true },
      },
      series: { color: "#059e8a" },
    },
    xAxis: {
      type: "datetime",
      dateTimeLabelFormats: { second: "%H:%M:%S" },
    },
    yAxis: {
      title: { text: "Temperature (Celsius)" },
      //title: { text: 'Temperature (Fahrenheit)' }
    },
    credits: { enabled: false },
  });
  setInterval(function () {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var x = new Date().getTime(),
          y = parseFloat(this.responseText);
        //console.log(this.responseText);
        if (chartT.series[0].data.length > 40) {
          chartT.series[0].addPoint([x, y], true, true, true);
        } else {
          chartT.series[0].addPoint([x, y], true, false, true);
        }
      }
    };
    xhttp.open("GET", "/temperature", true);
    xhttp.send();
  }, 10000);
  var chartH = new Highcharts.Chart({
    chart: { renderTo: "chart-Motor" },
    title: { text: "Motor" },
    series: [
      {
        showInLegend: false,
        data: [],
      },
    ],
    plotOptions: {
      line: { animation: false, dataLabels: { enabled: true } },
    },
    xAxis: {
      type: "datetime",
      dateTimeLabelFormats: { second: "%H:%M:%S" },
    },
    yAxis: {
      title: { text: "Humidity (%)" },
    },
    credits: { enabled: false },
  });
  setInterval(function () {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var x = new Date().getTime(),
          y = parseFloat(this.responseText);
        //console.log(this.responseText);
        if (chartH.series[0].data.length > 40) {
          chartH.series[0].addPoint([x, y], true, true, true);
        } else {
          chartH.series[0].addPoint([x, y], true, false, true);
        }
      }
    };
    xhttp.open("GET", "/humidity", true);
    xhttp.send();
  }, 10000);

  function myFunction() {
    var x = document.getElementById("myRange").value;
    document.getElementById("demo").innerHTML = x;
  }
  function myFunction2() {
    var x = document.getElementById("myRange2").value;
    document.getElementById("demo2").innerHTML = x;
  }

});
 
basti1012

basti1012

Well-known member
Dabei seit
12.06.2018
Beiträge
138
without the GET return I can only guess how it should work.
You deleted the old first line, which should have been in the second line.
Please test that
Javascript:
document.addEventListener("DOMContentLoaded", function(event) {
    function toggleCheckbox(element) {
        var xhr = new XMLHttpRequest();
        //if(element.id=="motor_on_off"){
        console.log(element.id);
        if (document.getElementById(element.id).checked == true)
            xhr.open("GET", "/update?button=" + element.id + "&motor_on_off=1&motor_interval=2&motor_mix=3", true);

        else
            xhr.open("GET", "/update?motor_on_off=4&motor_interval=5&motor_mix=6", true);
        //}
        xhr.send();
    }

    function set_ButtonState() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                // Typical action to be performed when the document is ready:
                alert(this.responseText);
                if (this.responseText == "1") {
                    document.getElementById("motor_on_off").checked = true;
                } else if (this.responseText == "0") {
                    document.getElementById("motor_on_off").checked = false;
                }
            }
        };
        xhttp.open("GET", "get_MotorState", true);
        xhttp.send();
    }


    var chartT = new Highcharts.Chart({
        chart: {
            renderTo: "chart-temperature"
        },
        title: {
            text: "BME280 Temperature"
        },
        series: [{
            showInLegend: false,
            data: [],
        }, ],
        plotOptions: {
            line: {
                animation: false,
                dataLabels: {
                    enabled: true
                },
            },
            series: {
                color: "#059e8a"
            },
        },
        xAxis: {
            type: "datetime",
            dateTimeLabelFormats: {
                second: "%H:%M:%S"
            },
        },
        yAxis: {
            title: {
                text: "Temperature (Celsius)"
            },
            //title: { text: 'Temperature (Fahrenheit)' }
        },
        credits: {
            enabled: false
        },
    });
    setInterval(function() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var x = new Date().getTime(),
                    y = parseFloat(this.responseText);
                //console.log(this.responseText);
                if (chartT.series[0].data.length > 40) {
                    chartT.series[0].addPoint([x, y], true, true, true);
                } else {
                    chartT.series[0].addPoint([x, y], true, false, true);
                }
            }
        };
        xhttp.open("GET", "/temperature", true);
        xhttp.send();
    }, 10000);
    var chartH = new Highcharts.Chart({
        chart: {
            renderTo: "chart-Motor"
        },
        title: {
            text: "Motor"
        },
        series: [{
            showInLegend: false,
            data: [],
        }, ],
        plotOptions: {
            line: {
                animation: false,
                dataLabels: {
                    enabled: true
                }
            },
        },
        xAxis: {
            type: "datetime",
            dateTimeLabelFormats: {
                second: "%H:%M:%S"
            },
        },
        yAxis: {
            title: {
                text: "Humidity (%)"
            },
        },
        credits: {
            enabled: false
        },
    });
    setInterval(function() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var x = new Date().getTime(),
                    y = parseFloat(this.responseText);
                //console.log(this.responseText);
                if (chartH.series[0].data.length > 40) {
                    chartH.series[0].addPoint([x, y], true, true, true);
                } else {
                    chartH.series[0].addPoint([x, y], true, false, true);
                }
            }
        };
        xhttp.open("GET", "/humidity", true);
        xhttp.send();
    }, 10000);

    function myFunction() {
        var x = document.getElementById("myRange").value;
        document.getElementById("demo").innerHTML = x;
    }

    function myFunction2() {
        var x = document.getElementById("myRange2").value;
        document.getElementById("demo2").innerHTML = x;
    }
})

If the code still does not run, check the console to see if there are any errors.

Or another idea. Test the attribute async
Javascript:
<script async src="app.js"></script>
 
Thema:

Problem with binding JavaScript data.

Oben