-2

I created a webUI to control a relay board with a raspberry pi.

When a button is pressed I access the relais.php with an AJAX request. The relais.php sends the corresponding commands to a python script from where the relays are controlled.

<!DOCTYPE html>
<html>
<body>
  <label class="switch">
  <input type="checkbox" id="IN1" onclick="in1()">
  </label>
</body>

<script>
  function in1() {
    var x = document.getElementById("IN1").checked;
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "relais.php?dir=IN1=" + x, true);
    xhttp.send();
    var out1 = x; }
</script>
</html>

The problem is the page gets reloaded the buttons are reset to the "unchecked" state. How could I store the states of the inputs on the webserver? The result would be that I could access the webUI from another device and the buttons would be "remembered" every time I reload.

0fd69cd8ff23
  • 45
  • 1
  • 7

2 Answers2

1

There are two ways to keep consistency across pages (that I can think of off the top of my head).

  1. You need to store the state in a database and/or in a server session.
  2. Otherwise you can store it within a cookie, and get the cookie contents, but cookies can be deleted and edited, so it might not be the best solution.

Example PHP:

<?php

// Set the header
header("Content-Type: text/json");

/* 
 * Create a Mysql connection with PDO
 * http://php.net/manual/en/pdo.construct.php 
 */

// Prepare a query
$sth = $dbh->prepare("select col1, col2, col3 from fruit where user_id = ? limit 1");

// Execute the query, and replace the `?` with the value of `$_GET['key']`
$sth->execute([$_GET['key']]);

// Get the row
$reslut = $sth->fetch();

// print the result to the page
echo json_encode($reslut);

Example jQuery ajax:

// Make a request to the php file with the key `123456`.
// This could be a user id, hash or whatever you want it to be
// as long as it is in the database.
// this example is using it as a user id.
$.get('/path/to/phpfile.php?key=123456', result => {
    console.log(result);
});
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
1

Q: How could i make the webbrowser know which buttons are in the "checked" state and which are "unchecked" every time i load the website?

A: If you want to "save state" with respect to a particular web browser, use cookies.

If you just want to "save state", you'll need some kind of "database" on the Web/PHP server.

MySQL is a good choice, but in your case ANYTHING would work: including something like a MongoDB noSQL database, or even a simple text file.

Personally, I would prefer a sever-side solution. But here's an example that uses jQuery and cookies - completely browser-side:

jQuery Toggle with Cookie

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190