So I tried Google before I posted this and didn't find anything that suited my needs. I was hoping you guys could help.
I have a form simple just a drop down box and a checkbox. The drop down box shows a list of names pulled from a database. The checkbox is initially unchecked. What I want to happen is that when the user clicks on the box the page will refresh and update the drop down box to include more names in the list depending up on the sql query that I have set up.
so form looks like this :
<form name="search" method="post" action="myaction.php">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
I think I may need some javascript but I wasn't sure I found several things that suggested just checking when the submit button is checked, but I need it to check before the form is submitted.
the sql statement is pretty simple just
$sql = "Select myID, fName, lName, extraNames from myTable $mysearch;
I want a where clause like this : (I know this isn't correct code but this is what I want it to do)
if checkbox is checked {
$mysearch = "";
}else {
$mysearch = "Where extraNames = 1";
}
I have some javascript that checks a checkbox on another page, but I couldn't figure out how to change the sql query (written in php) with the javascript. Thanks for any help you may provide.
HTML
<form name="search" method="post" action="myaction.php" id="myForm">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1" onclick="$('#myForm').submit();">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
PHP
$sql = "Select myID, fName, lName, extraNames from myTable";
if (!empty($_POST['checkActive'])) {
$sql .= "WHERE `extraNames` = 1";
}
Since the web page is running in a browser on the client side (the HTML) and the SQL query is running on the server (the PHP), you'll need to add a parameter to the page (the HTML) that indicates if the check box was clicked. When the form is submitted to the myaction.php URL on the server, you can then feed the value of that parameter into the if checkbox is checked statement.
Related
Can't find posts/answers that work for me. Everything in my page and modal works fine. I'm able fill the form out and select items in my dropdown the way i want. Issue is when i submit the form the page returns error 500 and says it's not working. Any help would be greatly appreciated, new to coding.
Following is one of the html dropdown items (i have three in the form + 2 input fields. As input fields they all worked fine and the form worked perfectly until i converted three to dropdowns):
<tr>
<td>
<label class="col-form-label col-form-label-sm">Department</label>
</td>
<td width="10"></td>
<td>
<select type="text" name="proj_dept" class="form-control form-control-sm" id="validationDefault01" required>
<option value="" selected disabled>Select</option>
<?php $result3 = $dbConn->query("SELECT * FROM a0_lists WHERE list_group='Departments' ORDER BY list_code ASC");
while($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
echo "<option value=".$row3['list_code'].">".$row3['list_code']."</option>";
} ?>
</select>
</td>
</tr>
Action php for form (again, this worked before I converted a couple fields to dropdowns:
`<?php require_once('../db.php');
$proj_name= $_POST['proj_name'];
$proj_desc= $_POST['proj_desc'];
$proj_priority= $_POST['proj_priority'];
$proj_status= $_POST['proj_status'];
$proj_dept= $_POST['proj_dept'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO a0_lists (proj_name, proj_desc, proj_priority, proj_status, proj_dept)
VALUES ('$proj_name', '$proj_desc', '$proj_priority', '$proj_status', '$proj_dept')";
$conn->exec($sql);
echo "<script>alert('Successfully Added!'); window.location='../proj/proj.php'</script>"; ?>`
I have a question.
I want to achieve something, however, I have never done this so unfortunately I do not know how to handle this.
In my screen I fill a dropdown box with names from a sql db.
Now I would like, as soon as a name is chosen from that dropdown that the other data be loaded such as, for example, min and max values.
I would like to use these values to, for example, be able to give limits to input fields.
So as soon as an entry field falls outside of the loaded values, the entry field then turns red.
However, I would like to use this without the submit button of the form being pressed.
Is this possible ? if so can someone help me with this?
The code i use to fill my selectbox is this.:
<td>
<div class="controls">
<select name="prod" id="employee" onclick="updateBottomValue(this.value);" onchange="mys1()" style="width: 245px;">
<option value="" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM specsv1 where RActive = 'y' order by RNaam";
$q = $pdo->prepare($sql);
$q->execute(array($Id,$RNaam));
Database::disconnect();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['Id'] . "'>" . $row['RNaam'] . "</option>";
}
?>
</select>
<?php if (!empty($ProductError)): ?>
<span class="help-inline"><?php echo $ProductError;?></span>
<?php endif; ?>
</div>
<span id="selectedValue"></span>
<input STYLE="width: 6em" name="rrss" type="text" id='rrss'>
</td>
The code i have to get the selected name is this.:
<script>
function updateBottomValue(selectedvalue) {
document.getElementById("selectedValue").innerHTML=selectedvalue;
document.getElementById('rrss').value = selectedvalue;
}
</script>
Yap it is possible.
And maybe this example ajax for what you want, feel free to modify to fit your requirements.
function viewMinMax(value){
if (value == 'a'){
tempurl = "https://api.myjson.com/bins/dv40y";
}else if (value == 'b'){
tempurl = "https://api.myjson.com/bins/egjmq";
}
$.ajax({
url: tempurl,
type: "get",
dataType: "JSON",
data: {}, //this is data you send to your server
success: function(res)
{
$('#info').show();
document.getElementById("info").innerHTML = 'Your min value: ' + res.min + ', Your max value: ' + res.max;
$('#min').val(res.min);
$('#max').val(res.max);
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<select name="product_select" id="product_select" onchange="viewMinMax(this.value)">
<option value="">Select Product</option>
<option value="a">Product A</option>
<option value="b">Product B</option>
</select>
<p id="info" style="display:none;"></p>
<h3>Load the min & Max</h3>
<label for="min">Min</label>
<input type="text" name="min" id="min" value="">
<br>
<label for="max">Max</label>
<input type="text" name="max" id="max" value="">
</form>
ignore the tempurl it can be change with your action to select data based on value to your DB.
Is it possible? Absolutely. There are a few ways of going about it. One easy way is to use jQuery to fire off what's called an AJAX call as soon as the dropdown value changes. The AJAX call your PHP script and get back some HTML that it will place wherever you want it on the screen.
It's a big subject, so difficult to give you exact answers, but google jquery ajax dropdown onchange and you should be able to get enough information to get you going. One of them is the following (there are many):
jQuery Load form elements through ajax, from onchange event of drop down box
I have an html form that I submit to a php server. If I submit the form the standard way with a submit button and an action="screen_custom.php", then it works fine. I see a page full of valid JSON data.
But if I submit the form using a jquery ajax call, then an empty json array is returned. I believe the php is unable to find the form values for some unknown reason. Anyway, how do I debug the php during an ajax call? The response must only include the data needed to populate a jquery DataTable. If I echo debugging output, then the datatable will fail to populate.
Here's some code that successfully submits the form to the php and returns good json data.
<form id="criteriaForm" method="post" action="screen_custom.php">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<input type="submit" value="Run">
</form>
Here's some code that fails to return the same json data:
<form id="criteriaForm" method="post" action="">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<button type="button" onclick="runCustomScreen()">Run</button>
</form>
And the javascript:
function runCustomScreen() {
$('#customTable').DataTable({
"ajax": {
type: 'POST',
url: "screen_custom.php",
data: $('#criteriaForm').serialize(),
complete: function(jqXHR, textStatus) {
console.log("Run was successful, textStatus="+textStatus);
},
error: function(e, textStatus, errorThrown) {
alert("textStatus="+textStatus +", errorThrown="+errorThrown);
}
}
});
return false; //needed if called by onclick event
}
Here's the parts of the php that handle the form data and return the json:
$upside = $_POST["upside"];
$sql = "SELECT * FROM stocks " .$where;
//echo '<script>'
//echo 'sql=' .$sql .'<br>';
//echo 'console.log(' .$sql .')';
//echo '</script>';
$rs = mysql_query($sql);
//store result in an array
$results = array();
while($row = mysql_fetch_object($rs))
{
$results[] = $row;
}
$data = json_encode($results);
echo '{"data":' .$data .'}';
//close the db connection
mysql_close($connection);
Note that if I uncomment any but the last echo, then the datatable won't populate. So how can I debug this?
I figured out how to debug it. In the chrome debugger, select the Network tab, then select "screen_custom.php" from the list, then select the Response tab. It shows the output from the php. I uncommented the echo sql statement and could see that in fact, the form parameters are not being read, as I suspected.
Then I googled on that problem and found the solution was to modify the data paramenter js as shown below:
data: function(d) {
var form_data = $('#criteriaForm').serializeArray();
$.each(form_data, function(key,val) {
d[val.name] = val.value;
});
},
I don't know why the first method didn't work as I could see the correct parameters being sent in the header. But this works.
Did you tried to use the isset($_POST['value']) method on your php script? where value is the name that you will assign to your submit button.
I am trying to displaying the input fields depending upon the what outputs are coming from the database. Please share any idea or logic in this. I have more than 25 fields.
Page1.php
I have Name(Text type), Email(Email type), gender(Radio), country(Select dropdown), Address( Textarea) in the form. The user will click on check box whatever he needs from the form and click on submit then the value of the fields which he selects will store in the database.
Form page
Page2.php
Here I am displaying the fields which are selected from Page1.php but also I need input type related to which fields come from the database.
For example: In the page1 I choose Name, Email, Country and submitted the form then In page2 I have to display the output <input type="text" name="Name">,<input type="text" name="Name">,<select></select>.
I need to know what logic I have to use it. Can any one help me with the script?
Form code
<form action="" method="post">
<input type="checkbox" name="check-fields[]" value="Name">
<label>Name(Text type)</label>
<input type="checkbox" name="check-fields[]" value="Email">
<label>Email(Email type)</label>
<input type="checkbox" name="check-fields[]" value="Gender">
<label>Gender(Radio type)</label>
<input type="checkbox" name="check-fields[]" value="Select">
<label>Country(Drop down)</label>
<input type="checkbox" name="check-fields[]" value="textarea">
<label>Address(Textare)</label>
<input type="submit" name="submit" value="submit">
</form>
Storing the value in the database
if (isset($_POST['submit'])) {
// prepare and bind
$a=$_POST['check-fields'];
$elements= implode(',',$a);
$sql_elements="INSERT INTO test (elements) VALUES (?)";
$stmt = $conn->prepare($sql_elements);
$stmt->bind_param("s", $elements);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
}
Page 2
I am getting output but how can I set the input fields?
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
You're trying to create a personalized form for different users if I'm correct, meaning that you will allow a user to generate a form based on a selection of fields the user can choose from.
What you need to do is create a table called "forminputtypes" where you create a row for each different input field you can think of, and want to give the user as a choice to select from. Your table would looke like this:
Id | FieldName | Type | etc ->
-------------------------------
1 | Name | text | ...
2 | Email | email | ...
3 | Gender | radio | ...
You can add more columns in the table to store more information (think of possible values in a radio input or a dropdown).
Now at in Page1.php you select all input types from this table, and display them like you already are. However, the value of these checkboxes will be the corresponding Id value of the record in the database like so:
<input type="checkbox" name="check-fields[]" value="3">
Now when someone chooses the Gender field, you can see in your Page2.php that the user did so by matching his choice '3' to the record in the database. If you want to save this information, you can create another table called UserFormInputFields which will function as a couple table between your user table and the FormInputTypes table.
When you want to display the form in Page2.php, you simply get all the input fields the user chose by selecting on Id from the FormInputTypes table. Since you know the type of each input field (because it's a column in the table) you can display them all correctly.
If you want to do it in core PHP only.Just put if else around the html tags.If value is coming from Database then you show particular tag else nothing. You can modify your page 2 code like.
<?php
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
<form action="" method="post">
<?php if(in_array("Name",$arr)) { ?>
<input type="text" name="name" >
<label>Name</label>
<?php } ?>
<?php if(in_array("Email",$arr)) { ?>
<input type="email" name="email">
<label>Email</label>
<?php } ?>
<?php if(in_array("Gender",$arr)) { ?>
<input type="radio" name="gender" value="Male">
<input type="radio" name="geneer" value="Female">
<label>Gender(Radio type)</label>
<?php } ?>
//.............write other fiels like this.
<input type="submit" name="submit" value="submit">
</form>
I hope this helped.
In my HTML code I have a table but with no data rows initially loaded, only a header and column labels. Upon clicking a button, a number of rows are loaded into this table depending how many rows are selected from the database in a SQL statement. In this situation, if my team has seven registered players in the database, my table will display seven rows (via PHP echo statements). In each row I have a checkbox with the players name and text input boxes.
This is the jQuery that adds rows once the post-result button is clicked:
$("#post-result").click(function(){
$("#post-result").hide();
$("#confirm-result").show();
$("#cancel").show();
$("#home-player-count").show();
$("#home-score").html("<input class='form-input f-score' id='home-score-input' type=number name=home_score maxlength=2>");
$("#away-score").html("<input class='form-input f-score' id='away-score-input' type=number name=away_score maxlength=2>");
$("#stats-home").after(<?php
echo "\"";
$i = 0;
$sql2 = mysqli_query($link, "SELECT * FROM user_accounts WHERE ps4_club= '" . $myclub . "'");
while ($row = mysqli_fetch_array($sql2, MYSQLI_ASSOC))
{
$i++;
echo "<tr id='player-".$i."'><td class='match-stats-name'><input type='checkbox' class='f-player' checked='true' value='" . $row['username'] . "' name='home_player_".$i."'>". $row['username'] ."";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_rating_1'> . <input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_rating_2'></td>";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_goals'></td>";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_assists'></td>";
echo "<td><input class='form-input f-stats' maxlength=2 name='home_player_".$i."_tackles_won'> / <input class='form-input f-stats' maxlength=2 name='home_player_".$i."_tackles_made'></td></tr>";
}
echo "\"";
?>)
<?php
$_SESSION["match_id"] = $id;
$_SESSION["player_count"] = $i;
$_SESSION["team"] = $team;
?>
$("#stats-home").after is where the rows get added.
The problem I'm coming across is when I'm trying to input this data from the table into my database. This is the bit of PHP code that is loaded once I click the confirm-result button of my form:
<?php
include "../config.php";
if (isset($_POST["confirm_result"]))
{
session_start();
for ($i = 1; $i <= $_SESSION["player_count"]; $i++)
{
$sql = $link->prepare("INSERT INTO ps4_apl_1_stats (match_id, team, name, rating, goals, assists, tackles_won, tackles_made)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param("issiiiii", $match_id, $team, $name, $rating, $goals, $assists, $tackles_won, $tackles_made);
$match_id = $_SESSION["match_id"];
$team = mysqli_real_escape_string($link, $_SESSION["team"]);
$name = "test_".$i."_player";
$rating = $_POST["home_player_".$i."_rating_1"];
$goals = $_POST["home_player_".$i."_goals"];
$assists = $_POST["home_player_".$i."_assists"];
$tackles_won = $_POST["home_player_".$i."_tackles_won"];
$tackles_made = $_POST["home_player_".$i."_tackles_made"];
$sql->execute();
$sql->free_result();
}
header("Location: ../match.php?id=".$_SESSION['match_id']);
}
else
{
header("Location: ../match.php?id=".$_SESSION['match_id']);
}
?>
What this code does is it loops through each row in the table by incrementing the $i variable. In each iteration it'll put the data from the input boxes into variables, which are then placed into the prepared SQL statement. Each row's input boxes have names that are numbered by what row number they are, for example:
ROW 1: home_player_1_goals, home_player_1_assists
ROW 2: home_player_2_goals, home_player_2_assists
ROW 3: home_player_3_goals, home_player_3_assists
When I try to submit this form, I get a lot of "Unidentified index" notices, like this:
Notice: Undefined index: home_player_1_goals in C:\Apache24\htdocs\script\match_post.php on line 20
For some reason it's not finding the POST variables of any of the input boxes that were inserted dynamically into the page via echo statements. It has no trouble finding $_POST["confirm_result"] since that input box is loaded into the page right at the beginning.
How do I get around this? It's pretty much not recognizing any of the input boxes that have been loaded in via echo statements.
I also dumped the $SESSION and $POST variables using print_r:
print_r($_SESSION): Array ( [email] => my_email#hotmail.com [userid] => 43 [xbox_club] => [ps4_club] => Wrecking Crew [match_id] => 3 [player_count] => 7 [team] => home )
print_r($_POST): Array ( [confirm_result] => Confirm Result )
It only shows the confirm_result button which is loaded onto the page initially.
I also have another question:
How would I go about skipping the insertion of a row depending on if it's checked or not? In each row I have a checkbox. When this checkbox is disabled, that rows input boxes will all be disabled. What would be the best way to skip this row? At the moment my code goes through every single row and enters the data, regardless of whether the input boxes are disabled or not.
Thanks in advance!
UPDATE - here is a single row that gets generated after the "post-results" button is clicked:
<tr id="player-1">
<td class="match-stats-name"><input type="checkbox" name="home_player_1" value="Syrian2nv" checked="true" class="f-player">Syrian2nv</td>
<td><input name="home_player_1_rating_1" maxlength="1" class="form-input f-stats single"> . <input name="home_player_1_rating_2" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_goals" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_assists" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_tackles_won" maxlength="2" class="form-input f-stats"> / <input name="home_player_1_tackles_made" maxlength="2" class="form-input f-stats"></td>
</tr>
Where is your form in relation to #stats-home? You're telling jQuery to add those form inputs after it, so if your form is inside it, they will miss the form.
If I were you, I would simplify the whole jQuery call you've got up there by outputting your fields when you load your page normally, but applying a class to the table row which you will tell to be invisible:
echo "<tr class='player-information' id='player-".$i."'><td class='match-stats-name'><input type='checkbox' class='f-player' checked='true' value='" . $row['username'] . "' name='home_player_".$i."'>". $row['username'] ."";
<style type="text/css">
.player-information {
display: none;
}
</style>
Then in your jQuery you replace $("#stats-home").after() with:
$('tr.player-information').show();
Not sure if this will fix your problem or not, but at least you'll know that your form elements are there, in the DOM and being output in the correct place (p.s. if this doesn't help, post the resulting HTML output on your page after you click your button so we can see what's happening)
--edit-- also, post the javascript produced when you load the page i.e. after PHP's done its thing
I'll answer the second question. As far as the first one I'm betting that the html isn't quite right after the jQuery insert based on the fact that the var_dump on the $_POST is empty.
The second question, skip a row if the checkbox isn't checked. So if your html is like this:
<tr>
<td><input type="checkbox" name="checkme[]"></td>
<td><input type="text" name = "homePlayerRating[]"></td>
<td><input type="text" name="homePlayerGoals[]"></td>
</tr>
<tr>
<td><input type="checkbox" name="checkme[]"></td>
<td><input type="text" name = "homePlayerRating[]"></td>
<td><input type="text" name="homePlayerGoals[]"></td>
</tr>
Then in the php when you process it do:
foreach($_POST['homePlayerRating'] as $key=>$homePlayerRating){
if(isset($_POST['checkme'][$key])){
//now you know that row was checked
$playerRating = $_POST['homePlayerRating'][$key];
$goals = $_POST['homePlayerGoals'][$key];
}
}
EDIT: This is dead wrong. I'm not sure what I was thinking. The $_POST['checkme'] array won't match the rest of the line. It isn't added to the $_POST array if it's not checked. For example if you check the checkbox in the third line down the
$_POST['homePlayerTating']
key will 2 but the
$_POST['checkme']
key will be zero because it isn't added to that array unless it's checked so it will be the first item in the $_POST['checkme'] array.