How to Fetch Data After Selecting from Dropdown List

How can I Fetch data after selecting from dropdown list

To get your selected value, you have to reach the $_GET or $_POST supertables after the user submits the form.

So, after the submit, get it as, if you POST:

<?php 
$employee_id = $_POST['employee_id']; ?>

If you GET:

<?php 
$employee_id = $_GET['employee_id']; ?>

Creating a Dropdown list by fetching data from backend

You could do something like this:

let result = {};
let allCourses = {};

function filterCourses() {
var filter = document.getElementById("inputFilter").value;
result.courses = allCourses.courses.filter(x => x.title.includes(filter))
let select = document.getElementById("one");

while (select.firstChild) {
select.removeChild(select.firstChild);
}

for (let i = 0; i < result.courses.length; i++){
let option = document.createElement("option");
option.value = result.courses[i]._id;
option.text = result.courses[i].title;
select.appendChild(option);
}
}

async function getCourses() {
let url = 'users.json';
try {
let res = await fetch("https://ffcc-app.herokuapp.com/get/courses");
return await res.json();
} catch (error) {
console.log(error);
}
}

async function renderCourses() {
allCourses = await getCourses();
result = Object.assign({}, allCourses);
let select = document.getElementById("one");
for (let i = 0; i < result.courses.length; i++){
let option = document.createElement("option");
option.value = result.courses[i]._id;
option.text = result.courses[i].title;
select.appendChild(option);
}
}

renderCourses()
<div class="container">
<form action="#" method="POST">
<h2>Course 1</h2>
<div class="select-box">
<div class="options-container">
<select class="option" id="one">
<option value="">Select a course.. </option>

</select>
</div>
<div class="selected">
Select Courses
</div>
<div class="search-box">
<input type="text" id="inputFilter" placeholder="Search..." onchange="filterCourses()"/>
</div>
</div>
</form>
</div>

Fetch data from mysql database based on multiple dropdown selections

You can check if the options are set by using
isset() and if the value is not set, Just assign '' a string of length zero to those variables.

if(isset($_POST['get_option1'])){
$state1 = $_POST['get_option1'];
}else{
$state1 = '';
}

Similarly for all other variables.

Want to fetch data from database based on dropdown list selection using php

$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);

You are searching in the column planname, but by defining the <option>'s as

echo "<option value=$row[id]>$row[planname]</option>";

You are sending the id as value.

So your query should be:

$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));

Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?

The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.

How to do implement your plan

You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)

1. The frontend:

As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).

To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.

So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.

Note:

I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp

I think you should check out jQuery if you haven't yet, it makes things really really easy.

Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.

I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.

<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';

try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>

2. The backend: (in this case called ajax.php)

A simple piece of code, nothing special to do.

First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.

Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.

Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.

Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.

<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';

if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}

try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}

$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}

How to fetch data from database from the second dropdown value

In order to update Processor dropdown, Socket dropdown will not cause any problem.

Check below link which has resolved this kind of question.

JavaScript - populate drop down list with array



Related Topics



Leave a reply



Submit