Fetching column value from DB for a Select Option - javascript

I've a drop-down list for selecting an Id on a php page, the values of which is getting fetched from the database(1st Column).
There's a text-field next to the drop-down in which I want to display the name of the member (2nd Column) from the database.
The code is below -
<?php
include ('connection.php');
$query = "SELECT Member_id FROM member_db ORDER BY Member_id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn)."[".$query."]");
?>
<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square onChange="showMember(this.value)"">
<option selected ="true" disabled="disabled">Select Member Id</option>
<?php while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){?>
<option value=" <?php $row['Member_id']; ?> ">
<?php echo $row['Member_id'];?>
</option>
<?php }?>
</Select>
<input style="min-height:30px" type="text" id="st_name" placeholder="Member name" name="ist_name" disabled/>
The JavaScript code I'm calling is this -
function showMember(str) {
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getMember.php?q="+str,true);
xmlhttp.send();
}
}
The getMember.php is another php file in which I'm firing a query to get the Member_name based on the value of Member_id.
But the problem is that somehow, that onChange, the page doesn't call the showMember() function.

1) Missing echo in value attribute <option value="<?php $row['Member_id']; ?> "> <?php echo $row['Member_id'];?>
2) onchange should be outside the class attribute .<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square" onChange="showMember(this.value)">
simple use jquery ajax
function showMember(str)
{
$.ajax({
url:'getMember.php',
type:'post',
data:{q:str},
success:function(data)
{
$('#st_name').val(data);
}
});
}
Note :don't forgot to include jquery

Related

Trigger JS function on pageload when populating select box from database

I have the following js script that triggers onChange of the select box below.
It then retrieves data from a table and returns some input fields populated with the data (using PHP code below). Then saves the data.
This part works fine.
However, if I run the script again, and it populates the selected option from DB and shows as a selected option, but it does not display the populated input fields returned from the PHP code/DB query since I am not triggering the onChange again.
I tried to add 'window.onload = showAgentOne;' under the JS for the onChange function, assuming it would see the value in (str) from the select box, but I am probably missing something as it does not work.
New to JS - I hope this makes sense.
JS:
function showAgentOne(str) {
if (str == "") {
document.getElementById("agent1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("agent1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user_agent1.php?q=" + str, true);
xmlhttp.send();
}
window.onload = showAgentOne; // trigger function on pageload - not working
HTML:
<select name="narid" onchange="showAgentOne(this.value)" class="form-control">
<option selected="selected" disabled value="">select agent</option>
<?php
$sql = "select last_name, first_name, active, nrds_id from ft_form_2 ORDER BY last_name";
$sql_result = mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($sql_result)) }?>
<option value="<?php echo $row[" nrds_id "]; ?>" <?php if($narid_agent1==$ row[ "nrds_id"]) { echo ' selected '; } ?> >
<?php echo strtoupper($row["last_name"]) . ' > ' . $row["first_name"] . ' ' . $row["last_name"] . ' ['.$active.']'; ?>
</option>
<? } ?>
</select>
<div id="agent1"></div>
PHP (user_agent1.php) ------------------------- $q=$_GET["q"]; $sql="SELECT pay_to_name,nrds_id FROM ft_form_2 WHERE nrds_id = $q"; $result = mysqli_query($mysqli,$sql); while($row = mysqli_fetch_array($result)) { ?>
<input type="text" name="narid_agent1" value="<?php echo $row['nrds_id']; ?>">
<input type="text" name="pay2_agent1" value="<?php echo $row['pay_to_name']; ?>">
<?php } ?>
'window.onload = showAgentOne;' is a good try but it is expecting a str param, otherwise it returns and do nothing. That's why nothing happens.
You will have to try something like
window.onload = function (event) {
let str = 'ADD_YOUR_VALUE_HERE';
showAgentOne(str);
}
But I can't help you with what str should be.

Put dropdown selection in variable and use in search query

I have 2 pages I am working with, index.php and dropdown-display.php. I have a dropdown in index.php that sends the selection to dropdown-display.php and filters my HTML table. I also have a search box, and if a dropdown selection has already been made, I want it to search the already filtered results by using the dropdown value in the query as well.
So how can I incorporate the variable $q below (if a dropdown selection has been made) into my search query?
This is what I currently have...
Index.php:
<?php
if(isset($_POST['search-species'])) {
// variable that brings in search value
$speciesToSearch = $_POST['SpeciesToSearch'];
// query used to filter results based on search
$sql = "SELECT *
FROM Example_Final_Structure
WHERE [Species] LIKE '%".$speciesToSearch."%'
ORDER BY [Current-SKU] ASC";
} else {
$sql = "SELECT *
FROM Example_Final_Structure
ORDER BY [Current-SKU] ASC";
}
?>
HTML in index.php:
<script>
// function that gets the value of the dropdown and sends it to display-dropdown.php to get results
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('millwork_table');
sorttable.makeSortable(newTableObject);
}
};
xmlhttp.open("GET","dropdown-display.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form name="myForm" action="">
<section id="supp_name_dropdown" onchange="hide2()" align="center" >
<select id="selectsupp" class="supp-name" data-attribute="supp" onchange="showUser(this.value)">
<option value="" selected disabled>Supplier Name</option>
<?php foreach($drop->fetchAll() as $dropdown) { ?>
<option class="sku-<?php echo $dropdown['Supplier-Name'];?>" value="<?php echo $dropdown['Supplier-Name'];?>"><?php echo $dropdown['Supplier-Name'];?></option>
<?php } ?>
</select>
</section>
</form>
<section id="search-species">
<form method="post" action="index.php">
<input name="SpeciesToSearch" class="search" type="text" placeholder="Species">
<span class="arrow"></span>
<button type="submit" class="button" name="search-species" value="Search">Search</button><br>
</form>
</section>
Dropdown-display.php:
<?php
$q = ($_GET['q']); //variable that holds dropdown selection value
$sql="SELECT *
FROM Example_Final_Structure
WHERE [Supplier-Name] = '$q'";
?>
In your search form you could add a <input type="hidden" id="searchsupp" name="searchsupp" value=""/>
then en your showUser function, inject the value received to the hidden input. document.getElementById("searchsupp").value = str;
Then you can use this value in your search by adding it to your query
"SELECT *
FROM Example_Final_Structure
WHERE ".($searchsupp != "" ? "[Supplier-Name] = '".$searchsupp."' AND ")."[Species] LIKE '%".$speciesToSearch."%'
ORDER BY [Current-SKU] ASC"
Where $searchsupp is the variable you make from the posted data.

Passing multiple variables to another page

I am trying to pass the variables from 3 dropdown menus to another page. The first dropdown (course) is dynamically loaded from the database and is passing to the other page fine. However the other 2 dropdowns, whose data is manually set is not passing to the other page.
<script>
function showCourse() {
var course = document.getElementById('selectCourse').value;
var year = document.getElementById('selectYear').value;
var semester = document.getElementById('selectSemester').value;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateTT.php?course="+course+"&year="+year+"&semester="+semester,true);
xmlhttp.send(null);
}//showCourse
Above is the script that gets the data and sends to other page
<?php
$db_host = 'localhost'; $db_user = 'root'; $db_pass = 'golftdi105'; $db_name = 'finalproject';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT CourseId, CourseName FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['CourseId'].'">'.$row['CourseName'].'</option>';
}
Above is the dynamically loaded dropdown
<select class="StyleTxtField" id="selectYear" >
<option value = "">Select Year</option>
<option value = "">1</option>
<option value = "">2</option>
<option value = "">3</option>
</select>
<select class="StyleTxtField" id="selectSemester" >
<option value = "">Select Semester</option>
<option value = "">1</option>
<option value = "">2</option>
</select>
<input type="submit" value= "submit" class="StyleButtonField" onclick="showCourse();" />
Above is the code that is hard coded.
$course = mysql_real_escape_string($_GET['course']);
$year = mysql_real_escape_string($_GET['year']);
$semester = mysql_real_escape_string($_GET['semester']);
Above is the code on the page the data is being passed to. I have tried echoing out these variables but only the COURSE variable is echoing out.
Thanks for any help, tried to include as much information as possible.
You don't have any values set in your hard-coded select options.
<option value="1">1</option>
...
All the options have the value set to "".. Set them to value="1" etc.

Using AJAX, PHP and MySQL to display table data

I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment

display multiple values from html form checkbox in another checkbox using AJAX, PHP and MYSQL

I have to select sub-category according to the category checked. i am stuck with selecting multiple checkboxes and displaying its value using ajax.
i want to use pure ajax and not jquery. i am fetching values of 1 checkbox from database table and now i need to display other checkbox with the values fetched with select query depending upon the multiple checkboxes user checks. i have an idea foreach loop is to be used but cant understand how and where to frame it..Please Help. Thank u.
this is the form:
<?php
while($f1=mysql_fetch_row($res)) {
?>
<input type="checkbox" name="chkcat[]" id="chkcat" onChange="showUser(this.value)" value='<?php echo $f1[1]; ?>'> <?php echo $f1[0]; ?>
<? } ?>
<div> id="txtHint"> </div>
Ajax code that has showUser function
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_chkbox.php?q="+str,true);
xmlhttp.send();
}
</script>
and the file that has to fetch sub category according to the category selected and url i.e:ajax_chkbox.php is:
while($row = mysql_fetch_array($result))
{
echo "<input type=checkbox name=chksubcat[] id=chsubkcat value= $row[0]> $row[2]";
echo "<br>";
}
You can change Dropdown to checkbox
select_cat.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "select_subcat.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subcat").html(html);
}
});
});
});
</script>
Category :
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
include('databasefile');
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
$sql=mysql_query("select cat_name from category order by cat_name");
while($row=mysql_fetch_array($sql))
{
$cname=$row['cat_name'];
echo '<option value="'.$cname.'">'.$cname.'</option>';
} ?>
</select> <br/><br/>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>
2.select_subcat.php
<?php
include('databasefile);
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select s_name from subcat_l1 where cat_name='$id'");
while($row=mysql_fetch_array($sql))
{
$sname=$row['s_name'];
echo '<option value="'.$sname.'">'.$sname.'</option>';
}
}
?>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>

Categories

Resources