Submit form onchange checkbox and update mysql db - javascript

<?php
if(isset($_POST['chkStatus'])){
for ($i=0;$i<count($_POST['chkStatus']);$i++) {
$count = count($_POST['chkStatus']);
list($txtClientId, $txStatusValue) = explode('-', $_POST['chkStatus'][$i], 2);
$stmtChkStatus=$con->query("SELECT id,status FROM users WHERE id=$txtClientId");
$SRow = $stmtChkStatus->fetch();
if($SRow['status']!=$txStatusValue) {
if($txStatusValue==0) $stmtStatus=$con->query("UPDATE users SET status='0' WHERE id=$txtClientId");
else $stmtStatus=$con->query("UPDATE users SET status='1' WHERE id=$txtClientId");
}
}
}
?>
<html>
<body>
<dl>
<?php $stmtUsers=$con->query("SELECT id,status FROM users");
while($UsersRow = $stmtUsers->fetch()){
echo "<dt>$UsersRow[name]</dt>
<dd><input type='checkbox' name='chkStatus[]' value='$UsersRow[id]-$UsersRow[status]'";
if($CRow['status']==0) echo " checked";
echo " onchange='this.form.submit()'>
</dd>";
?>
</dl>
</body>
</html>
The issue with my code is that it only execute the checked checkboxes. I need a code that changes the status in SQL DB of the checkbox that i click(onchange).

Instead of looping through $_POST['chkStatus'] you could fetch all possible values with $con->query("SELECT id,status FROM users") and loop over those values. You can check then, if $_POST['chkStatus'] is set for the according value(s).

At a moment you send all checkbox values to the server. You may send only interested values. Quick and dirty solution:
split you checkboxes into individual forms and submit only form you need:
while($UsersRow = $stmtUsers->fetch()){
echo "<dt>$UsersRow[name]</dt>
<form .... > <!-- Here required attributes -->
<dd><input type='checkbox' name='chkStatus[]' value='$UsersRow[id]-$UsersRow[status]'";
if($CRow['status']==0) echo " checked";
echo " onchange='this.form.submit()'>
</form>
</dd>";
In inclick attribute take id or name of checkbox and add to request.

Related

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

Output Data From MYSQL Table Into HTML Form Depending On User Choice

I have a MYSQL table (roomcost) that holds the costs of hiring rooms.
costID Room Cost
1 room1 15
2 room2 30
3 room3 50
rsRoomCost SQL is: SELECT * FROM roomcost
The HTML form has checkboxes that allow the hirer to make the choice of Room 1, Room 2 or Room 3. The hirer can hire one, any two or all three rooms.
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</div>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</div>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</div>
The form also has an input box (that will be hidden, once I get it working) for each room that will be filled with the appropriate cost from the table. When the form is submitted, the hirers record would hold the choice of room(s) and cost paid by that hirer at the time of hiring.
The JS script that checks if a particular checkbox is selected and would output the cost to the relevant input box.
function Check() {
if (document.forms["bookform"].room1.checked) {
document.forms["bookform"].thisRoom1.value = "<?php echo($row_rsRoomCost['room1']; ?>";
} else if (document.forms["bookform"].room2.checked) {
document.forms["bookform"].thisRoom2.value = "<?php echo($row_rsRoomCost['room2']; ?>";
} else if (document.forms["bookform"].room3.checked) {
document.forms["bookform"].thisRoom3.value = "<?php echo($row_rsRoomCost['room3']; ?>";
}
}
The input boxes for the output are:
Room 1: <input type="text" name="thisRoom1" value="">
Room 2: <input type="text" name="thisRoom2" value="">
Room 3: <input type="text" name="thisRoom3" value="">
As you see, I'm trying to use php to fill in the relevant value from the database table. However, this, of course, only shows the cost from the first record in the costs table regardless of which room is checked.
How do I get the cost of the chosen room from the table into the correct input box on the form?
I've tried <?php echo($row_rsRoomCost['room1']) where ($row_rsRoomCost['costID']) = '1'; ?> but this doesn't work. I thought about 'case' statements but don't know how that would work. The only way I can think of is a seperate SQL statement for each room. eg: SELECT * FROM roomcost WHERE costID = 1
How do I get the cost of the selected room from the table into the correct input box on the form?
Going through your code I find that that would be the long way round of solving it .
The first step to solving it would be to put your data into a reusable front End source like JSON (it easier to work with ).
Example: (Results are in the console log F12)
<?php
$servername = "localhost";
$username = "root";
$password = "jono23";
$dbname = "helpothers";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `roomcost`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// echo "id: " . $row["costID"]. " - Name: " . $row["room"]. " " .$row["cost"]. "<br>";
// data you want to send to json
$data[] = array(
'id' => $row['costID'],
'room' => $row['room'],
'cost' => $row['cost']
);
//}
}
} else {
echo "0 results";
}
$conn->close();
$json_data = json_encode($data);
//print_r($json_data);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id='bookform' >
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</input>
<input type="text" name="room1value" readonly><br>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</input>
<input type="text" name="room2value" readonly><br>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</input>
<input type="text" name="room3value" readonly><br>
</form >
<script type="text/javascript">
var Rooms = JSON.parse('<?php print_r($json_data) ; ?>');
console.log(Rooms);
function Check() {
//room1
if (document.forms["bookform"].room1.checked)
{
document.forms["bookform"].room1value.value = Rooms[0].cost;
console.log(Rooms[0].cost);
}else{
document.forms["bookform"].room1value.value ='';
}
//room2
if (document.forms["bookform"].room2.checked)
{
document.forms["bookform"].room2value.value = Rooms[1].cost;
console.log(Rooms[1].cost);
}else{
document.forms["bookform"].room2value.value ='';
}
//room3
if (document.forms["bookform"].room3.checked)
{
document.forms["bookform"].room3value.value = Rooms[2].cost;
console.log(Rooms[2].cost);
}else{
document.forms["bookform"].room3value.value ='';
}
}
</script>
</body>
</html>
By encoding the SQL query results into a json array first you able to
close the database connection so not to use up unnecessary resources
on multiple requests
Then By calling that PHP JSON Object into JavaScript you can more easily apply it to your html and JavaScript Needs
Converting PHP Data To JSON and parse with JavaScript Help us work with things like rest api's
This is the main reason why JSON implementation can be found in many languages as its an easy way to share data across different coding languages
Another suggestion that I would make for the handling of the data is not to store the values in a checkboxes . Create another text input for that purpose and store them there . e.g
<input type='text' id='gethandle1'>
<script>
let box1 = document.getElementById('gethandle1');
box1.value = Rooms[0].cost;
</script>
I hope this helps you .

How to show input type text after submit if checkbox checked

I GOT 2 Questions
1)
So, below is the code that will keep user's checkbox checked after user submitted the form, so that he know which one he had checked and dont need to fill again.
But the question is it did not show the array, i guess is the
echo ($_POST['ao']);
I tried use print_r,but it show out all the array, i just want to echo out the specific item that user checked.Currently it just echo "Array".
2)
It did now display the input type text if user is checked after submit.But before submit, it works.
function ao1Function(){document.getElementById("ao1").value =
document.getElementById("ao1").disabled = false;
document.getElementById("ao1").style.display = "inline-block";}
function ao1Function2(){document.getElementById("ao1").value = document.getElementById("ao1").style.display = "none";
document.getElementById("ao1").disabled = true;
}
<input type="checkbox" name="cbox[]" value="Basic Add To Cart,0" onclick="if(this.checked){ao1Function()}else{ao1Function2()}"
<?php if (isset($_POST['cbox']) && in_array("Basic Add To Cart,0",$_POST['cbox'])){echo 'checked';}?>>
Basic Add To Cart<div id="ao1" style='display:none;'>
<input type="text" id="ao" min="0" step="0.05" name="ao[]" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric' placeholder="Amount (RM)"
value="<?php if(isset($_POST['ao'])) echo ($_POST['ao']);?>" <?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'";?>></div>
1) Here's how to show only the selected check-boxes
var_dump(array_filter($_POST['ao'], function($v) {return $v == 'true';}));
2) The JavaScript part looks OK. You might need a little fix on the PHP side and it will work perfect.
before:
<?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'";?>
after:
<?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'"; else echo "style='display:none;'";?>

PHP get input value without submit

Guys i have foreach loop where i list some prices. All price have own input radio button.
By default only one price from looping is checked. I want to get that value when page is lodaed.
I have one session where i store number of days. Based on these days I get the price of cars.
$numDays = $_SESSION['days']; // 5
$calculate_km = $numDays * 140; // 5*140km
So in page where i want to show total KM i use:
if(isset($_SESSION['days']) {
$numDays = $_SESSION['days'];
}else {
// Show default selected radio button value
}
Problem is bcs price list with radio is on the some page and there is no sumbiting
My loop:
<?php if($prices = getCarPricePeriod($car->ID, $od, $do)):?>
<?php $first = true; ?>
<?php foreach ($prices as $price): ?>
<tr>
<td><input type="radio" name="price" value="<?= $price['value'];?>" <?= $first ? 'checked' : '' ?>> </td>
<td><input type="text" name="price_name" value=" <?= $price['name'];?>">€/per day</td>
</tr>
<?php endforeach; ?>
<?php $first = false; ?>
<?php endif; ?>
Total KM : <span> <?= $numDays * 140 ;?> </span>
Only is posible to get that value if i submit that form. So i need js for this or any way to do this in php
I want to get that value when page is lodaed.
Use .ready() , selector $("tr input:checked") , .val()
$(document).ready(function() {
var val = $("tr input:checked").val()
})
If what you are asking is "how to send data from client-side to server-side", then the answer is AJAX.
Take a look at W3School's AJAX tutorial here: http://www.w3schools.com/ajax/
EDIT 1
for javascript, this should do it:
document.querySelector("input[type=radio]:checked").getAttribute("value")
Without submit, you need JavaScript to do that, like this:
<script>
var p = document.getElementByName("price");
</script>

changing data output with onchange event

I have an option box which lists the users of something in my site. I then have two input boxes. One for wins and another for losses. I am trying to create an onchange event, so that whenever a certain user is selected from the option box, the php will output that users info. As of now the output is not changing. What am I doing wrong with my onchange event?
function myFunction() {
var wins_var = document.getElementById('wins');
var losses_var = document.getElementById('losses');
}
PHP that outputs the data and html with inputs
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
echo "<select name = 'member' onchange='myFunction()'>";
while ($row = $stmt->fetch()) {
echo "<option value = '{$ranking_user_id}' data-wins = '{$ranking_wins}' data-losses = '{$ranking_losses}'";
echo ">{$ranking_firstname}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}?><br><br>
<label>Wins
<input type="text" value="<?php echo $ranking_wins; ?>" id="win">
</label>
<label>Loss
<input type="text" value="<?php echo $ranking_losses; ?>" id="losse">
</label>
You're on the right lines, and you don't need to do any Ajax just to achieve what you asked in your question.
The main problem is that in your Javascript, you get a reference to the two inputs for wins and losses, but you don't actually assign any value to them.
Assuming you're using jQuery (as you tagged it), then it's much easier to use this for the onchange binding and value assignments.
Firstly, you just need to make sure your "member" select has an ID instead (or as well) as a name, and you don't need the "onchange" as we'll bind that with jQuery:
echo "<select id = 'member'>";
Then, your Javascript just needs to look like this:
$(document).ready(function() {
$("#member").change(function() {
myFunction();
});
myFunction();
});
function myFunction() {
$selectedOption = $("#member option:selected");
$("#wins").val($selectedOption.data("wins"));
$("#losses").val($selectedOption.data("losses"));
}
The initial $(document).ready() function sets up the onchange binding to call myFunction(), and the second myFunction() call just ensures the wins and losses inputs are populated for the default selected option on the initial page load.
JS Fiddle here: http://jsfiddle.net/fa0kdox7/
Oh yes, and finally, your wins and losses inputs just need to look like this:
<label>Wins
<input type="text" value="" id="wins">
</label>
<label>Loss
<input type="text" value="" id="losses">
</label>
Note that I corrected a couple of typos in their IDs.

Categories

Resources