PIsingh
Posts: 12
Joined: Tue Dec 24, 2013 11:52 pm

help with php web GPIO

Thu Jan 16, 2014 10:06 pm

I am a beginner for php & ajax or html for that matter. I have experience in java and c++ but lately i am learning some scripting languages. I am trying to do a very very basic web app with php & ajax, where i will enter a value of 1 in a text html form. And ajax sends that value to php using httprequest, and finally in my php i can play around that value that i get from ajax.
Perhaps pass that value into the GPIO function like this
$gpio->output(14, $x); //x is the value that i send by ajax and received by php
I am just assuming this might work :?
I am also using php gpio library, as my gpio code works fine when i run it from the command line. Like php filename.php, the led turns on.
My question is how do i go about doing a simplest experiment possible? && Does my approach makes sense?
Below is the code.......
HOPEfull i have explained this well :? please ask more question as i probably missed stuffff.....

OH for the output on my html page i get all the echo statements in my php file but the led doesn't turn on?

Code: Select all

<?php
$x =  $_POST['firstname'];
require '/home/pi/intoYourPath/vendor/autoload.php';
use PhpGpio\Gpio;
$x = 1;
echo "Setting up pin 14\n";
$gpio = new GPIO();
$gpio->setup(14, "out");
echo "Turning on pin 14\n";
$gpio->output(14, $x);
echo "Sleeping!\n";
sleep(3);
echo "Turning off pin 14\n";
$gpio->output(14, 0);
echo "Unexporting all pins\n";
$gpio->unexportAll();

?>
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
  
    var url = "my_parse_file.php";
 
    var fn = document.getElementById("first_name").value;

    var vars = "firstname="+fn;
    
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
  
    hr.onreadystatechange = function() {

	    if(hr.readyState == 4 && hr.status == 200) {

		    var return_data = hr.responseText;
	
		document.getElementById("status").innerHTML = return_data;

	    }
 
   }
    // Send the data to PHP now... and wait for response to update the status div
 
   hr.send(vars); // Actually execute the request

    document.getElementById("status").innerHTML = "processing...";

}

</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Value from ajax to php server: <input id="first_name" name="first_name" type="text" /> 
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>

Return to “General discussion”