Populating a dependent dropdown with AJAX, PHP and MYSQL - javascript

I'm trying to populate a dropdown with id='gymnasts' based on the value of another dropdown with id='classes'.
I understand that I must use AJAX, however after following multiple different tutorials I cannot seem to make the second aforementioned dropdown display any options whatsoever.
My code is as follows:
reports.php:
<script>
function getGymnasts(val){
alert('gets');
$.ajax({
type:"POST",
url:"ajax_populate.php",
data: 'classid='+val,
success: function(data){
$("$gymnasts").html(data);
}
});
}
</script>
<form method="post">
<table>
<tr><td>Select Class:</td><td><select id="classes" onChange="getGymnasts(this.value)" placeholder="Select Class" required/>
<?php $classes = mysqli_query($GLOBALS['link'], "SELECT * FROM classes;");
foreach($classes as $class){
echo('
<option value="'.$class['id'].'">'.$class['level'].'</option>
');
}?>
</select></td></tr>
<tr><td>Select Gymnast:</td><td>
<select id="gymnasts" placeholder="Select Gymnast" required/>
</select></td></tr>
<tr><td>Report:</td><td><textarea name="body" cols="60" rows="20" placeholder="Report text" required/></textarea></td></tr>
<tr><td>Progression Grade:</td><td><input type="text" name="progression" placeholder="A" required/></td></tr>
<tr><td>Effort Grade:</td><td><input type="text" name="effort" placeholder="A" required/></td></tr>
<tr><td></td><td><input type="submit" name="saveReport" value="Save"><input type="submit" name="savesendReport" value="Save and Send"></td></tr>
</table>
</form>
ajax_populate.php
include('dbconnect.php');
$classid = $_POST['classid'];
$sql = "SELECT * FROM gymnasts WHERE classid = '$classid'";
$result = mysqli_query($GLOBALS['link'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg ='<option value="'. $row["id"] .'">'. $row["name"] .'</option>';
}
}
else{$msg .="No Gymnasts were found!";}
echo ($msg);
mysqli_close($GLOBALS['link']);
Please help!

You are using wrong selector for gymnasts id, use # instead of $ in your success callback like
success: function(data){
$("#gymnasts").html(data);
// ^ change $ to # here
}
Also, make an option if no result found
else{$msg .="<option>No Gymnasts were found!</option>";}

Related

PHP / SQL: Multiple delete data using Select Option

Now I create a system that can delete multiple data using select option. But here I got some issues. When i only select one data, and press button delete, it will delete. But if I choose more than one data, for example, 3 data, it will only delete the latest id of the data. Below is my the image
And below is my code:
index.php
<form method="post" id="multiple_select_form">
<select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br /><br />
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
insert.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Can anyone knows how to solve this problem? Thanks
framework will hold one value every time.
Use input arrays -
Change name="framework" to name="framework[]".
and in query -
WHERE framework_id in ('". implode("','", $_POST["framework_id"]) ."')"
Try to use parameter binding for security.

select not sending $_POST data

I am confused as to why my select is not passing any post data to the results page. If I run var_dump($_POST); the select (#boxdest or #boxdest2) is not being displayed. Is there some special way to pass select to php results page. What I normally do is as an example: $var=$_POST['boxdest'];. Problem is the select is not being sent from original code. I have posted my code and would be grateful if someone could show me where I have gone wromg. Many thanks.
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("sample",$conn);
$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}'");
?>
<select id="boxdest" name="boxdest[]"size="7">
<?php
$i=0;
while($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
$i++;
}
?>
</select>
<input type="button" id="submit2" name="submit2" value=">" />
<input type="button" id="submit3" name="submit3" value="<" />
<select id="boxdest2" name="boxdest2[]" size="7"></select>
<script type="text/javascript">
$("#submit2").click( function()
{
//alert('button clicked');
$box1_value=$("#boxdest").val();
$box1_text=$("#boxdest option:selected").text();
$("#boxdest2").append('<option value="'+$box1_value+'">'+$box1_text+'</option>');
$("#boxdest option:selected").remove();
});
$("#submit3").click( function()
{
//alert('button3 clicked');
$box2_value=$("#boxdest2").val();
$box2_text=$("#boxdest2 option:selected").text();
$("#boxdest").append('<option value="'+$box2_value+'">'+$box2_text+'</option>');
$("#boxdest2 option:selected").remove();
}
);
</script>

Use value from a form in a redirect button outside the form

Fetch selected value from dropdown which is in one form and onClick of the button outside the form send the value to php page
<div class="drpvendorname">
<font style="color: white;">
<label>Distribution Point:</label>
</font>
</div>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option onClick="distribution('.$result['pointshortname'].')" value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form><!--form1 ends here-->
<form action="../customer/form.php"><!--form2 starts here-->
<button class="btn pos7" name="abc" method="GET" style="margin-left:5%;">New Customer</button>
</form><!--form2 ends here-->
<div class="dailybreakupbtn">
<input class="btn" type="submit" id="dailybreakupbutn" name="dailybreakup" value="Enter Daily Breakup" onClick="distribution(<?=$pointname?>)"/>
</div>
<?php
if(isset($pointname)){
?>
<script type="text/javascript">
function distribution(pointname){
var pointname;
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<?php
}
?>
I have tried this sending selected dropdown box value to next page using function name distribution
I ended sending undefined to the next page.
can any one help me sending the selected value to the next page with out putting the button in the <form>
May this will be help you :)
Html code:
<form action= "" method= "post">
<select class="form-control drpvendor" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="'.$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form>
JQuery Code:
$(doucment).on('change','.drpvendor',function(){
var data=$(this).attr('selected','selected');
$.ajax({
url: "dailybreakup.php",
data:'query='+ data,
type: "POST",
success: function(data) {
window.location.href='customer/form.php';
}
});
});
Use code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> // please link the path or use cdn
<script type="text/javascript">
function call_me(){
var pointname=document.getElementById("drpvendor").value;
alert(pointname); // comment it after testing
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<form>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
<input type="button" onclick="call_me()"/>
</form><!--form1 ends here-->
Note : 1) Code is not tested
2) use your select id instead of your_select_id
3) check variable

save selected options [<select> values in database

i need to save selected options values in database . In form, I need to include select options inside input type , Basically i have this code.
<form method="post">
<td>Designer order number </td>
<td>
<div id="ordernumbers">
<select>
<option>Select Order</option>
</select>
</div>
</td>
<input type="text" name="dueDate" value=""/>
<input name="register1" type="submit" id="btnSubmit" value="Update"
onclick="return updatepayment(); "/>
</form>
To include select option inside form , i tried as link1 but did't worked for me.
than i followed below code as in mentioned in link2
<form>
<td>
<div id="ordernumbers">
<input type="text" name="designerorder_id" list="citynames">
<datalist id="citynames">
<option>Select Order</option>
</datalist>
</div>
</td>
</form>
still i am getting Notice: Undefined index: designerorder_id error , but instead of above code , if i use this code : <input type="text" name="designerorder_id" /> i am not getting any error, so i guess i am doing in mistake in putting select inside input in form, please help me for this....
EDit
if (isset($_POST['register1'])) {
$designerorder_id = trim($_POST['designerorder_id']);
$product_id = trim($_POST['product_id']);
$paid_status = password_hash($_POST['paid_status'], PASSWORD_DEFAULT);
$due_date = trim($_POST['due_date']);
$stmt = $reg_user->runQuery("SELECT * FROM order_details");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
if ($reg_user->register1($designerorder_id, $product_id, $paid_status, $due_date)) {
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = " updated database";
// $subject = "Confirm updation";
// $reg_user->send_mail($email, $message, $subject);
$msg = "database updated ";
} else {
echo "sorry , Query could no execute...";
}
}
Note : i am requesting downvoter, please inform in comments reason for downvote so that i can correct it....

Based on a forms input value, how 2 generate selections 4 a drop down menu w row/record data from a database that will prefill a form when selected?

I'm trying to figure out a way to pre fill a form with data with past form information submitted in the past.
I have a form and a database. In my form I have a input named email that holds the pre-loaded default value of logged in member's email address that is read-only.
PIC
http://oi57.tinypic.com/2iubb4j.jpg
How can I generate a selection under a drop down menu that when selected will pre-fill the form with row/record data from my database?
and how can I generate only the records that match the forms input value 'email' to the records with the same value under the 'email' column in the database?
I've been at it for weeks now and can not seem to find any sense of direction on how to achieve this. Can't really find any tutorials site, video, sample code or anything close on how to make this possible. Any help would be great...thanks for your help in advance.
FORM
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<option value="xxx">SAMPLE SELECTION</option>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo#gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
PHP FILE
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
UPDATE: closest thing below so far...but wont work...not sure it covers the matching the email values portion...thanks anyways 'edcoder'
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$query='select * from tablename';
$res=mysql_query($query);
while($row=mysql_fetch_array($res))
{
?>
<option value="<?php echo $row['feildname']; ?>"><?php echo $row['feildname']; ?></option>
<?php
}
?>
</select>
It seems that you're almost there.
Try this.
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>

Categories