Put dropdown selection in variable and use in search query - javascript

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.

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.

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

Fetching column value from DB for a Select Option

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

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.

Dynamically updating content of drop down menu when radio button value is changed using PHP, MySQL and AJAX

I am creating a form and in it there are two radio buttons and a drop down list. I want when a user changes their choice of radio button, the drop down list also changes its values which will picked from a database table with two columns with names life and general.
Here is a snippet of the request.php
<input type="radio" name="department" id="department" value="life" onchange="listDept(this.value)" checked>Life
<input type="radio" name="department" id="department" value="general">General
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<select name="department" id="listDept">
</select>
Here is the getdepartment.php file to query the database:
<?php
require 'connectdb.php';
$department =NULL;
if(isset($_POST['department'])){$department = $_POST['department']; }
if($department == "life")
{
$query = "select life from tbl_departments";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
echo '<option>'.$row['life'].'</optiom>>';
}
if($department == "general")
{
$query = "select general from tbl_departments";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
echo '<option>'.$row['general'].'</option>';
}
Here is the AJAX script to check the user's choice:
function listDept()
{
var dept = document.getElementById("department").value;
var xhr;
if (window.XMLHTTPRequest) { //Mozilla, Safari...
xhr = new XMLHTTPRequest();
}
else if (window.ActiveXObject) { //IE8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "department" + dept;
xhr.open("POST", "./parse_files_php/getdepartment.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data(){
if(xhr.readyState==4){
if (xhr.status==200) {
document.getElementById("listDept").innerHTML = xhr.responseText;
}
else {
alert('There was a problem with the request.');
}
}
}
}
I am not getting any feedback from the server i.e. the drop down list is not populated.
My database connections are working fine.
In case youre willing to use jquery for the page scripts for that one functionality
you can refer to my sample.
HTML:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$("input[name='department']").click(function() {
//console.log($('input:radio[name=department]:checked').val());
getSelectOptions($('input:radio[name=department]:checked').val());
//AJAX CALL
});
});
function getSelectOptions(radioVal) {
$.ajax({
type: 'POST',
url: 'dbo.php',
data: {'radioval': radioVal},
success: function(data) {
//console.log(data);
updateSelect(data)
}
});
}
function updateSelect(data) {
var json = $.parseJSON(data);
console.log(json);
var selectHTML;
$.each(json, function(key, value) {
console.log(value);
selectHTML += "<option value=" + value + ">" + value + "</option>";
});
$('#listDept').html(selectHTML);
}
</script>
</head>
<body>
<form>
<input type="radio" name="department" id="department" value="life">Life
<input type="radio" name="department" id="department" value="general">General
<select name="department" id="listDept">
</select>
</form>
</body>
</html>
and my dummy php file that returns the list entries which obviously will contain your database calls and so forth.
dbo.php
<?php
$radio=$_REQUEST['radioval'];
$selectArray=array();
if($radio=='life'){
$selectArray[0]='life1';
$selectArray[1]='life2';
}else if($radio=='general'){
$selectArray[0]='general1';
$selectArray[1]='general2';
}
echo json_encode($selectArray);
Try the sample and let us know if this works for you.

Categories

Resources