Dependent combo boxes in PHP and Ajax - php

I need help with my code. I want to select values from the database based on the first combo box selection.
The first combo box has subject ID, which I want to use in my SQL to find the value of the second combo box.
<form class ="form_group" id="form1" enctype="multipart/form-data" method="POST" action="uploadstudent.php">
StudentID:<br>
<input type="text" name="StudentID" value="<?php echo $_SESSION['login_user'];?>"readonly>
<br><br>
Subject ID:<br>
<select id="soflow" name="SubjectID" onChange="getState(this.value);">
<option>
<?php
mysql_connect("localhost", "id503120_course", "12345678");
mysql_select_db('id503120_course_db');
$StudentID=$_SESSION['login_user'];
$Course = mysql_query("SELECT course FROM student WHERE StudentID = '".$StudentID."'");
$result = mysql_fetch_assoc($Course);
$newcourse = implode($result);
$query=mysql_query("SELECT SubjectID FROM subjects WHERE Course= '".$newcourse."' AND SubStatus = 'Y'");
if(!$numrows=mysql_num_rows($query)==0)
{
while($row=mysql_fetch_assoc($query))
{ ?>
<option value="<?php echo $row['SubjectID']; ?>">
<?php echo $row['SubjectID']; ?>
</option>
<?php }
}
else{
echo "No submissions are currently open for you";
}
?>
</select>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "submission.php",
data:'SubjectID='+val,
success: function(data){
$('#soflow2').html(data);
}
});
}
</script>
Assign number: <br><select id="soflow2" name="AssessmentNum">
<option>
<?php
mysql_connect("localhost", "id503120_course", "12345678");
mysql_select_db('id503120_course_db');
if(!empty($_POST["SubjectID"])) {
$query ="SELECT AssignNum FROM subjects WHERE SubjectID = '".$_POST['SubjectID']."'";
while($row=mysql_fetch_assoc($query))
{ ?>
<option value="<?php echo $row['AssignNum']; ?>">
<?php echo $row['AssignNum']; ?>
</option>
<?php }
}
?>
Here in assign number, I am not able to view any information at all.
Please help me.

The problem is in the parameter SubjectID in the ajax request. try this:
function getState(val) {
$.ajax({
type: "POST",
url: "submission.php",
data:{'SubjectID' :val},
success: function(data){
$('#soflow2').html(data);
}
});
}

Related

Not Getting a POST value from ajax

I have a select dropdown and a textfield in my form. So i tried using $.ajax whenever i choose a value in dropdown, the textfield will show an output based on the selected value from the dropdown. But im always getting an error undefined variable from ff.php. I tried to pin down the cause, and what i found is im not getting any POST value in ff.php. Any solution for this ? Thanks in advance.
Here is my code in prs.php
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:'productid='+val,
success: function(data){
$("#brandss").val(data);
}
});
}
</script>
<td><select name="drpcode" onchange="getState(this.value)" class="form-control name_list"><?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?></option><?php } ?></select></td>
<td><input type="text" id="brandss" name="brand" placeholder="Brand" class="form-control name_list" required value=""></td>
Here my codes in ff.php
<?php
require_once("conn.php");
$id = $_POST['productid'];
$query = mysqli_query($conn,"SELECT productbrand FROM products WHERE productid = '$id' ");
while($rs = mysqli_fetch_array($query,MYSQLI_BOTH)) {
$brand = $rs['productbrand'];
}
echo $brand;
?>
Please add the data in json format and specify the datatype as json in ajax function
$.ajax({
url: "ff.php",
type: "POST",
data: {
productid : val
// more fields can be added here
},
dataType: 'json',
success: function(return){
// process success
},
error: function(err) {
// Process failure
}
});
I think the format of ajax data attribute is wrong . You should try this :
data:{productid:val}
UPDATE :
you should select both productid and product code in select statement
<td>
<select name="drpcode" onchange="getState(this.value)" class="form-control
name_list">
<?php $drp = mysqli_query($conn,"SELECT productid,productcode FROM
products");
while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo
$dp['productcode']; ?></option><?php } ?>
</select>
</td>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:{productid:val},
success: function(data){
$("#brandss").val(data);
}
});
}
Try running the query before select and then display result with loop-
<?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); ?>
<select name="drpcode" onchange="getState(this.value)" class="form-control name_list">
<?php while ($dp = mysqli_fetch_array($drp)) { ?>
<option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?>
</option><?php } ?>
</select>

Second Dropdown concern, Php, Ajax

This code comes from a guide I've seen in YouTube.
I'm trying to populate the second dropdown based on the choices on the first dropdown, in my test page its working, however when I tried to attach it to my main page, the second dropdown is not turning into a dropdown.
I've tried to re-code it, but still the problem persist.
This is for the AJAX
<?php
include('db.php');
if($_POST['id']){
$id=$_POST['id'];
if($id==0){
echo "<option value='0'>Select Type</option>";
}else{
$sql = mysqli_query($con,"SELECT * FROM `ConcernType` WHERE Concern_Id='$id'");
while($row = mysqli_fetch_array($sql)){
echo '<option value="'.$row['ConcernType_id'].'">'.$row['ConcernType_name'].'</option>';
}
}
}
?>
This is for the index.php
<label>Concern Category :</label><select name="concerncategory" class="concerncategory">
<option value="0">Select Category</option>
<?php
include('db.php');
$sql = mysqli_query($con,"select * from ConcernCategory");
while($row=mysqli_fetch_array($sql))
{
echo '<option value="'.$row['Concern_Id'].'">'.$row['ConcernCategory_name'].'</option>';
} ?>
</select><br/><br/>
<label>Concern Type :</label><select name="concerntype" class="concerntype">
<option value="0">Select Type</option>
</select>
<br /><br />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".concerncategory").change(function()
{
var Concern_Id=$(this).val();
var post_id = 'id='+ Concern_Id;
$.ajax ({
type: "POST", url: "ajax.php", data: post_id, cache: false,
success: function(Type) {
$(".concerntype").html(Type);
} }); }); });
</script>
Here are some screenshots.
https://ibb.co/2NTTdG8
https://ibb.co/fFXBzFS

get php variable from dropdown without page submission

I am trying to get a value from a dropdown menu and pass it as a php variable and echo it (on the same page).
The dropdown displays the name of users, but select their username, which I want to echo. The purpose it to use the variable to perform other tasks, if I can echo it successfully.
I have used jquery and ajax to get the variable, without submitting the page. But I am unable to get the php variable.
I have read several examples, and used them, but somehow my code is not working.
Can anyone please suggest where is the mistake?
Here is my code:
Test2.php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php",
data:{username : user},
type:'POST',
success:function(response) {
$("#usermame").html(response);
}
});
});
});
</script>
<?php
if (isset($_POST['username'])){
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?>
<?php
if (isset($_GET['username'])){//only echo user name if requested from js do not include header or footer
$username = $_GET['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}else{//you can include here your headers
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td> </tr> <tr><td> <span id="username">
<?php if (isset($_POST['username'])){//show if submitted from html form
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?> </span></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php?username="+user,
success:function(response) {
$("#username").html(response);
}
});
});
});
</script>
<?php
//you can include here your footers
}
?>
Your success handler is printing the request content in a html element with id username that do not exists on the page (at least not on this snippet)
success:function(response) {
$("#usermame").html(response);
}
Try to make the POST request to a different file because, in your case, the printed content will include the select (and the db request) again.

how to post data with ajax, php and bootstrap select

I am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through
Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});

hold values of dropdown using ajax

there are two drop downs naming country and state.....so how to hold the values whwn error occurs in the form.i have used ajax to list the state value
<select name="country" onchange="getstate(this.value,'')">
<option value="">Select</option>
<?php $option="";
$query="select * from tbl_country";
$res=mysql_query($query);
while ($country=mysql_fetch_array($res)) {?>
<option value="<?php echo $country['id']; ?>"><?php echo $country['country']; ?></option>
<?php }?>
</select>
<select id="state" >
</select>
/////ajax code///////
<script type="text/javascript">
function getstate(id) {
$.ajax({
type : 'post',
url : 'ajax.php',
data : {
act : 'get_state',
country : id,
},
success : function(data) {
data = data.replace(/\s*\n\s*/g, '');
if (data) {
document.getElementById('state').innerHTML = data;
} else {
}
return true;
}
});
}
</script>
///////ajax.php/////
if($_REQUEST['act']=="get_state"){
$statelist=array();
$countryid=$_REQUEST['country'];
$query="select * from tbl_state where id_country=".$countryid;
$result=mysql_query($query);
$option.='<option value="">select</option>';
while ($state=mysql_fetch_array($result)) {
$option.= '<option value="'.$state["state"].'">'.$state["state"].'</option>';
}
echo $option;
}
I want to hold both the values of country and state at the time of form submit(error occurs). how to do that?

Categories