Pass value of a variable from an html page to a php file

Asked

Viewed 734 times

1

I am trying to control the brightness of an led using a Raspberry Pi3 and a web interface developed by me. I have a text area with two buttons, one that increases the value and another that decreases the value (the value varies between 0 and 10), what I’m trying to do is whenever I press the increase or decrease button send the value to a php file which in turn passes the value to Raspberry. I also have an image that simulates the light on or off and wanted to make a condition so that if the light is off this value is not sent, and even if the page refresh the status is maintained. Someone knows how to do it, I’m already using Xmlhttprequest to open the php file but I don’t know how to transfer the variable that is in php ($value).

Página web:

Php code:

<?php
 system ( "gpio mode 1 pwm" );
 system ( "gpio pwm 1 $valor" );
 sleep(5);
 system ( "gpio pwm 1 0" );

?>

HTML code

<!DOCTYPE html>
<html>
	<head>
	
	<meta name="description" content="Framset - Como usar frames em sites HTML">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
	
	<script language="Javascript" > <!-- regulação de luminusidade de 0 a 10 -->
        function mais1z1 () {
                             var dec = parseInt(zona1.textgol.value);
              if (dec>=10){
                   zona1.textgol.value=10;
                   $valor=102,4*10;
              }else{
                   zona1.textgol.value=dec+1;
                   $valor=102,4*dec+1;
              }
        }
        function menos1z1 () {
              var dec = parseInt(zona1.textgol.value);
              if (dec<=0){
                   zona1.textgol.value=0;
              }else{
                   zona1.textgol.value=dec-1;
              }
        }     
            		
		
	</head>
	<body>

  
		

		<article>  
		<div id="luz">
			<h1>Controlo de Luz</h1>
  
 ZONA 1.
  
  

<script type="text/javascript">


        $(document).ready(function() {

$('#aumentar').click(function(){

var a= new XMLHttpRequest();

a.open("GET", "luz.php"); a.onreadystatechange=function(){

if(a.readyState==4){ if(a.status ==200){

 } else alert ("http error"); } }

a.send();

});

});

$(document).ready(function() {

$('#diminuir').click(function(){

var a= new XMLHttpRequest();

a.open("GET", "luz.php"); a.onreadystatechange=function(){

if(a.readyState==4){ if(a.status ==200){

 } else alert ("http error"); } }

a.send();

});

});

</script>
  
		<img id="myImage" onclick="changeImage1()" src="pic_bulboff.gif" width="50" height="90">  
		<center>  
			<form name="zona1" action="file:///media/tiago/BA1C46441C45FBBF/Users/Tiago/Dropbox/Pesta/Control Center/form.cgi" method="POST"> <!-- passagem de dados para codigo em c -->
			<input type="button" id="aumentar" value='+' onclick='mais1z1()'>
			<input type="text" size="5" name="textgol" value="0">
			<input type="button" id="diminuir" value='-' onclick='menos1z1()'>
			</form>
		</center>

		

		<script>
			function changeImage1() {
				var image = document.getElementById('myImage');
				if (image.src.match("bulbon")) {
				image.src = "pic_bulboff.gif";
				<!-- inserir variável para definir estado OFF -->
				} else {
				image.src = "pic_bulbon.gif";
				<!-- inserir variável para definir estado ON -->
				}
			}
		</script>
		
 
		<a href="javascript:window.history.go(-1)">Voltar</a>
		
		

</div>

	</body>
</html>

  • You need to update the variable $valor in the PHP file every time you call the function mais1z1 ()? No need to update also when calling the function menos1z1 ()?

  • I need to upgrade both functions, but to test I’m trying first with one.

2 answers

1

I am using the following php code to try to print the value received in a function, and whenever in the system function ( "gpio pwm 1 $_SESSION['textgol1']" ); I change the value to the variable $_SESSION['textgol1'] the html page responds with http error, if you put a number, for example 500, works correctly, someone knows the problem?

Html code:

<!DOCTYPE html>
<html>
	<head>
	
	<meta name="description" content="Framset - Como usar frames em sites HTML">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
	
		<script language="Javascript"> <!-- regulação de luminusidade de 0 a 10 -->
        function mais1z1 () {
                             var dec = parseInt(zona1.textgol1.value);
              if (dec>=10){
                   zona1.textgol1.value=10;
              }else{
                   zona1.textgol1.value=dec+1;
              }
        }
        function menos1z1 () {
              var dec = parseInt(zona1.textgol1.value);
              if (dec<=0){
                   zona1.textgol1.value=0;
              }else{
                   zona1.textgol1.value=dec-1;
              }
        }        
        </script>       
		<script language="Javascript">  <!-- regulação de luminusidade de 0 a 10 -->
        function mais1z2 () {
							 var dec = parseInt(zona2.textgol.value);
              if (dec>=10){
				   zona2.textgol.value=10;
              }else{
				   zona2.textgol.value=dec+1;
              }
        }
        function menos1z2 () {
			  var dec = parseInt(zona2.textgol.value);
              if (dec<=0){
				   zona2.textgol.value=0;
              }else{
				   zona2.textgol.value=dec-1;
              }
        }        
        </script>      
		<script language="Javascript">  <!-- regulação de luminusidade de 0 a 10 -->
        function mais1z3 () {
							 var dec = parseInt(zona3.textgol.value);
              if (dec>=10){
				   zona3.textgol.value=10;
              }else{
				   zona3.textgol.value=dec+1;
              }
        }
        function menos1z3 () {
			  var dec = parseInt(zona3.textgol.value);
              if (dec<=0){
				   zona3.textgol.value=0;
              }else{
				   zona3.textgol.value=dec-1;
              }
        }        
        </script>   
		<script language="Javascript">  <!-- regulação de luminusidade de 0 a 10 -->
        function mais1z4 () {
							 var dec = parseInt(zona4.textgol.value);
              if (dec>=10){
				   zona4.textgol.value=10;
              }else{
				   zona4.textgol.value=dec+1;
              }
        }
        function menos1z4 () {
			  var dec = parseInt(zona4.textgol.value);
              if (dec<=0){
				   zona4.textgol.value=0;
              }else{
				   zona4.textgol.value=dec-1;
              }
        }        
        </script>     		
		
	</head>
	<body>

  
		

		<article>  
		<div id="luz">
			<h1>Controlo de Luz</h1>
  
  <p>ZONA 1.</p>
  
  
  
  
 
  
		<img id="myImage" onclick="changeImage1()" src="pic_bulboff.gif" width="50" height="90">  
		<center>  
			<form name="zona1" action="file:///media/tiago/BA1C46441C45FBBF/Users/Tiago/Dropbox/Pesta/Control Center/form.cgi" method="POST"> <!-- passagem de dados para codigo em c -->
			<input type="button" id="botaomais" value='+' onclick='mais1z1()'>
			<input type="text" size="5" name="textgol1"  value="0">
			<input type="button" id="botaomenos" value='-' onclick='menos1z1()'>
			</form>
		</center>

		

		<script>
			function changeImage1() {
				var image = document.getElementById('myImage');
				if (image.src.match("bulbon")) {
				image.src = "pic_bulboff.gif";
				<!-- inserir variável para definir estado OFF -->
				} else {
				image.src = "pic_bulbon.gif";
				<!-- inserir variável para definir estado ON -->
				}
			}
			
		</script>
		
		
		 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script type="text/javascript">// <![CDATA[

$(document).ready(function() {

$('#botaomais').click(function(){

var a= new XMLHttpRequest();
var dados= '?textgol1='+ $("input[name='textgol1']").val();

a.open("GET", "luz.php" + dados); 

a.onreadystatechange=function(){

if(a.readyState==4){ if(a.status ==200){

 } else alert ("http error"); } }

a.send();

});

});


$(document).ready(function() {

$('#botaomenos').click(function(){

var a= new XMLHttpRequest();
var dados =  '?textgol='+ $("input[name='textgol']").val();

a.open("GET", "luz.php" + dados); 

a.onreadystatechange=function(){

if(a.readyState==4){ if(a.status ==200){

 } else alert ("http error"); } }

a.send();

});

});

</script>

		<p> ZONA 2.</p>
		<img id="myImage2" onclick="changeImage2()" src="pic_bulboff.gif" width="50" height="90">
		<center>  
		<form name="zona2">
        <input type="button" name="botaomais" value='+' onclick='mais1z2()'>
        <input type="text" size="5" name="textgol" value="0">
		<input type="button" name="botaomenos" value='-' onclick='menos1z2()'>
        </form>
		</center>

		

<script>
function changeImage2() {
    var image = document.getElementById('myImage2');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff2.gif";
    } else {
        image.src = "pic_bulbon2.gif";
    }
}
</script>
<p>ZONA 3.</p>
<img id="myImage3" onclick="changeImage3()" src="pic_bulboff.gif" width="50" height="90">
<center>  
		<form name="zona3">
        <input type="button" name="botaomais" value='+' onclick='mais1z3()'>
        <input type="text" size="5" name="textgol" value="0">
		<input type="button" name="botaomenos" value='-' onclick='menos1z3()'>
        </form>
</center>


<script>
function changeImage3() {
    var image = document.getElementById('myImage3');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff2.gif";
    } else {
        image.src = "pic_bulbon2.gif";
    }
}
</script>
  
  <p>ZONA 4.</p>
  <img id="myImage4" onclick="changeImage4()" src="pic_bulboff.gif" width="50" height="90">
 <center>  
		<form name="zona4">
        <input type="button" name="botaomais" value='+' onclick='mais1z4()'>
        <input type="text" size="5" name="textgol" value="0">
		<input type="button" name="botaomenos" value='-' onclick='menos1z4()'>
        </form>
</center> 


<script>
function changeImage4() {
    var image = document.getElementById('myImage4');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff2.gif";
    } else {
        image.src = "pic_bulbon2.gif";
    }
}
</script>
 
		<a href="javascript:window.history.go(-1)">Voltar</a>
		
		

</div>

	</body>
</html>

Php code:

 <?php

session_start();



if(isset($_GET['textgol1'])){
    $_SESSION['textgol1'] = $_GET['textgol1']*102.4;
   
    system ( "gpio mode 1 pwm" );
     system ( "gpio pwm 1 $_SESSION['textgol1']" );
     
}


if(isset($_GET['refresh'])){
    if(isset($_SESSION['textgol1'])){
        echo $_SESSION['textgol1'];
    }
}

     
?>

1

You can send data to the php script, more or less like this:

$('#aumentar').click(function(){

    var a= new XMLHttpRequest();

    //dados a serem enviados (input com name textgol)
    var dados =  '?textgol='+ $("input[name='textgol']").val();
    a.open("GET", "luz.php" + dados); 

    a.onreadystatechange=function(){

      if(a.readyState==4){ if(a.status ==200){
      } else alert ("http error"); } }

      a.send();
    });

  });

Assuming you’re including jquery (since you’re using $). In the above case the data is sent via http get method. This data can be received on the server like this:

<?php
//para poder persistir informações entre requisições diferentes
session_start();

//alterar o valor (escala 0 a 10)
if(isset($_GET['textgol'])){
    $_SESSION['textgol'] = $_GET['textgol'];
    //faça alguma coisa .... extra
}

//condição para verificar se é um refresh de pagina
//e retornar um valor previamente armazenado em $_SESSION
if(isset($_GET['refresh'])){
    if(isset($_SESSION['textgol'])){
        echo $_SESSION['textgol'];
    }
}
  • In order to print the value in php using for example the system() command which variable has the saved value that was received from html? It is $textgol, getting system ("gpio pwm 1 $textgoal") thus printing on pin 1 of gpio the value of textgol?

  • Yes, it would $_SESSION['textgol']

  • When I press the button (+) or the button (-) of the html page I receive the message ( http error). I have the php file configured as suggested and inside the first iftenho the system command("gpio pwm 1 $_SESSION['textgol']") to be able to print the value that is in the text field of the html page on pin 1, but I get the error I mentioned and in the case, if it replaces $_SESSION['textgol'] by a number, for example 500, I get no error and the led that is connected to pin 1 lights up. There is no other way to pass the value to the system command than with $_SESSION['textgol']?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.