So i just got my new raspberry pi in the mail and have been playing around with it for a bit.
Now, i want to be able to turn a LED on using a PHP code.
Let's say i got the following image:
<img src="images/On.png">
How can i make it so that when i click on that button, it runs the following PHP code without going to a different page?
system ( "gpio mode 7 out" );
system ( "gpio write 7 1" );
I already tried the following using a button, which worked:
<?
if ($_POST['submit'])
{
system ( "gpio mode 7 out" );
system ( "gpio write 7 1" );
}
if ($_POST['submit2'])
{
system ( "gpio mode 7 out" );
system ( "gpio write 7 0" );
} ?>
<form method="post" action="">
<input type="Submit" name="submit" value="On">
<input type="Submit" name="submit2" value="Off">
</form>
But now i'd like to have this with an image, but the same code doesn't seem to work that way.
Thanks in advance.
You could use jQuery's $.ajax
Just give the img
an id
and you can do something like this: (example)
$("img#light-on").click(function(){
$.ajax({
type: "POST",
url: "light-on.php",
data: {lighton: "true"},
success: function(){
$("p.status").html("The light is on!");
}
});
});
You then have to just run the same thing for img#light-off
and go to light-off.php
.
You need to load jQuery in like this:
<script src="jquery-1.11.2.min.js"></script>
and then run the code in a seperate script
:
<script>
$(document).ready(function(){
$("img#light-on").click(function(){
$.ajax({
type: "POST",
url: "light-on.php",
data: {lighton: "true"},
success: function(){
$("p.status").html("The light is on!");
}
});
});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.