I am working on a project where data about therapists is stored in a database, I have 5 dropdowns on my page and I want the data to be fetched based on the dropdown values selected by the user.
<div id="dropdowns">
<form method="post">
<?php
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$sql = "SELECT DISTINCT `Designation` FROM `therapists`";
if($res = $mysqli->query($sql))
{
echo '<div class="select">
<select id="profession" name="profession" onchange="getSelectDesignation(this.value);">
<option selected disabled>Filter by Profession</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Designation'] ."'>" . $row['Designation'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$ids = "SELECT DISTINCT `Identifies As` FROM `therapists`";
if($res = $mysqli->query($ids))
{
echo '<div class="select">
<select id="idas" name="idas" onchange="getSelectIdentifiesas(this.value);">
<option selected disabled>Identifies as</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Identifies As'] ."'>" . $row['Identifies As'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$clgr = "SELECT DISTINCT `Client Group` FROM `therapists`";
if($res = $mysqli->query($clgr))
{
echo '<div class="select">
<select id="clgr" name="clgr" onchange="getSelectClientGroup(this.value);">
<option selected disabled>Client Group</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Client Group'] ."'>" . $row['Client Group'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$istr = "SELECT DISTINCT `Issues Treated` FROM `therapists`";
if($res = $mysqli->query($istr))
{
echo '<div class="select">
<select id="istr" name="istr" onchange="getSelectIssuesTreated(this.value);">
<option selected disabled>Issues treated</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Issues Treated'] ."'>" . $row['Issues Treated'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$lan = "SELECT DISTINCT `Languages` FROM `therapists`";
if($res = $mysqli->query($lan))
{
echo '<div class="select">
<select id="idas" name="lan" onchange="getSelectLanguages(this.value);">
<option selected disabled>Languages</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Languages'] ."'>" . $row['Languages'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
?>
</form>
</div>
Whenever a user selects a dropdown option, a specific function for each dropdown gets called which takes the value of the option selected and sends it to a different page called fetch_data which displays the information about the therapists.
function getSelectDesignation(val1)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIdentifiesas(val2)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option2:val2,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectClientGroup(val3)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option3:val3,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIssuesTreated(val4)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option4:val4,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectLanguages(val5)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option5:val5,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
Below is the code in my fetch_data page :
<?PHP
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$state1 = $_POST['get_option1'];
$state2 = $_POST['get_option2'];
$state3 = $_POST['get_option3'];
$state4 = $_POST['get_option4'];
$state5 = $_POST['get_option5'];
$loc = $_SESSION['location'];
$find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')";
if ($result = $mysqli->query($find)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["Therapist ID"];
$field2name = $row["Name"];
$field3name = $row["Designation"];
$field4name = $row["Identifies As"];
$field5name = $row["Client Group"];
$field6name = $row["Languages"];
$field7name = $row["Issues Treated"];
$field8name = $row["Location"];
$field9name = $row["Phone Number"];
$field10name = $row["Intro"];
$field11name = $row["Instagram Link"];
$field12name = $row["Linkedin Link"];
$field13name = $row["Aasha URL"];
echo '<div id="profile-card">
<div id="info">
<div class="name-desig-img">
<div class="name-desig">
<a class="therapist-name" href="http://localhost/aasha/profile.php/'. $field2name .'">';echo $field2name;echo'</a>
<p>';echo $field3name;echo'</p>
</div>
<div class="p-img">
<img class="prof-img" src="';echo $field14name;echo'">
</div>
</div>
<div class="intro">
<p>';echo $field10name;echo'</p>
</div>
<div class="location">
<p>';echo $field8name;echo'</p><p>
</div>
</div>
<div id="links">
<div id="t-socials">
<div class="tp"><a class="t-links" href="';echo $field13name;echo'">';echo' Profile </a></div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field12name;echo '"><i class="fab fa-linkedin">';echo'</i></a> </div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field11name;echo '"><i class="fab fa-instagram-square">';echo'</i></a></div>
</div>
<p class="showphone">
<span class="clickshow" style="display: inline;"><b>Show Phone Number</b></span>
<span class="hiddenphone" style="display: none;">
<span>';echo $field9name;echo'</span>
</span>
</p>
</div>
</div>';
}
/*freeresultset*/
$result->free();
}
?>
Now the issue is whenever I select a dropdown option the value for the other dropdowns is empty and I get the undefined array key error in PHP. For example, if I select option1 which is the first dropdown, I get undefined array key error for option2, option3, option4, and option5. If I select option2 I get undefined array key error for option1, option3, option4, and option, and so on. I need to find a way to make the query work even if no option is selected in 1 or more dropdowns.
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.
First of all, only 1 request can be made in ajax at once, according to your code, the request is sent when onchange() so only 1 request will be made.
Everything looks fine but you are fetching all variables from _POST where as only 1 is sent at a time, so, you need to send all the variables at a time for your query $find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')"; to work.
Do something like this.....
<div id="dropdowns">
<form>
<!-- Your selectors here -->
<select id="idas" name="lan">
<option> ...... </option>
</select>
<select id="clgr" name="lan">
<option> ...... </option>
</select>
<select id="istr" name="lan">
<option> ...... </option>
</select>
<input type="button" onclick = "gettheValues()" value="GetIt">
</form>
</div>
Java script
function gettheValues()
{
var val1 = document.getElementById("idas").value;
var val2 = document.getElementById("clgr").value;
var val3 = document.getElementById("istr").value;
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
get_option2:val2,
get_option3:val3
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});//Send values all together...
}
I guess nothing need to be changed in php code.
And I need to find a way to make the query work even if no option is selected in 1 or more dropdowns. what you meant by this?
If those states state1 - state5 are important for your query then it is not possible to run that query.
It is you who know the importance of the states in that query so it won't be appropriate to answer.
If you think you can query as per different selectors do like this.
<?php
if(isset($_POST['get_option1']))
{
//appropriate query here
$query = "Your query with option1";
}
if(isset($_POST['get_option2']))
{
//appropriate query here
$query = "Your query with option2";
}
...
..etc to option5
//Here your result of query with html
?>
For any queries comment below, if you need a working example I will make one.
Related
I want to populate the drop-down based on the selection of other. Here's how the database looks like. Tried the following code but it isn't giving me any results.
make
id maker
2 Apple
3 Samsung
model
id make_id model
1 3 Galaxy S III
2 3 Galaxy S IV
3 2 iphone 5s
4 2 iphone 5
Queries.php
class Queries{
public static function getMaker() {
$conn = DB::databaseConnection();
$sql = "SELECT * from make" ;
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
public static function getModel($make_id) {
$conn = DB::databaseConnection();
$sql = "SELECT * from model WHERE make_id = :make_id" ;
$stmt = $conn->prepare($sql);
$stmt->bindParam(':make_id', $make_id);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
}
mobilereg.php
$make_id = filter_input(INPUT_GET, "make_id");
require_once './pages/header.php';
require_once './functions/queries.php';
$maker = Queries::getMaker();
$model = Queries::getModel($make_id);
<div class="control-group form-group">
<div class="controls">
<label>Make</label>
<select class="form-control"name="maker"id="maker"onchange="get_models();">
<option selected disabled></option>
<?php
for ($i = 0; $i < count($maker); $i++) {
echo '<option value="' . $maker[$i]['id'] . '">' . $maker[$i]['maker'] . '</option>';
}
?>
</select>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Model</label>
<select class="form-control" name="get_models" id="get_models">
<option selected disabled></option>
</select>
</div>
</div>
main.js
function get_models(){
var maker = $('#maker').val();
var dataString = "maker="+maker;
$.ajax({
type: "POST",
url: "functions.php",
data: dataString,
success: function(html)
{
$("#get_models").html(html);
}
});
}
functions.php
require_once './queries.php';
$make_id = filter_input(INPUT_POST, "make_id");
if($_POST){
$maker = $_POST['maker'];
if($maker!=''){
echo Queries::getModel($make_id);
echo "<select name='get_models'>";
echo "<option value='" . $row['make_id'] . "'>" . $row['model'] . "
</option>";
echo '</select>';
}
}
So maker and model are the two drop-downs. The options in the model should result on the basis of the selection we make in the maker drop-down.
I've referred the code from one the questions here but it doesn't work at all. The problem is in the functions.php I guess. I'm very new to php and js, any help would be appreciated. TIA
I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.
I am trying to get multiple value from multiple select textbox and use the same value in PHP for adding the SUM.
My code is:
function get_amount() {
var x = $('#work').val();;
alert(x);
$.ajax({
type: "POST",
url: "get-sum.php",
data: 'id=' + x,
success: function(data) {
alert(data);
//$('#html').load(document.URL + ' #html');
}
});
}
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose" name="work[]" id="work" onchange="get_amount()">
<option value="1" >option 1</option>
<option value="2"> OPtion 2 </option>
<option value="3"> OPtion 3</option>
</select>
And My php file as :
$id = $_POST['id'];
function getAmount($id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT
(amount)
FROM work
WHERE id = ?
");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $amount;
}
$sql = getAmount($id);
echo $sql;
Error which i am getting is the data which i am getting from multiple select is like 5,6,7 and its always hitting the php file at id 5. And the second problem how i will be able to add all $sql data.
I have done some changes in my PHP code :
$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
return $amount['total'];
}
I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}
`I have a script that is returning the right values except for one little problem. Lid is returning 892 which is right, However; Cid which should return 16 its returning 89216 a combination of the two. How can I get Cid to just return 16?
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString ='Lid='+ $(this).val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: LocationString,
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var Lid = $('#Doggie').val(), // This is the value of the id="Doggie" selected option
Cid = $(this).val(); // This is the value of the id="Kitty" selected option
$.ajax({
type: "POST",
url: "ajax_area.php",
data: {"Lid":Lid,"Cid":Cid},
cache: false,
success: function (html) {
$(".Pig").html(html);
}
});
});
});
</script>
</head>
<body>
<div id="frame1">
<label>Place :</label>
<select name="Doggie" class="Doggie" id="Doggie">
<option selected="selected">--Select Place--</option>
<?php
$sql = mysql_query("SELECT tblLocations.RestID as Lid, tblRestaurants.RestName as name
FROM tblRestaurants INNER JOIN tblLocations ON tblRestaurants.RestID = tblLocations.RestID
GROUP BY tblLocations.RestID, tblRestaurants.RestName
ORDER BY tblRestaurants.RestName ASC");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].'">'.$row['name'].'</option>';
} ?>
</select>
<label>City :</label>
<select name="Kitty" class="Kitty" id="Kitty">
<option selected="selected">--Select City--</option>
</select>
<label>Area: :</label>
<select name="Pig" class="Pig" id="Pig">
<option selected="selected">--Select Area--</option>
</select>
</div>
</body>
</html>
ajax_city.php
<?php
require('config.php');
if($_POST['Lid'])
{
$Lid=$_POST['Lid'];
//$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblCities.CityName as name
FROM tblLocations INNER JOIN tblCities ON tblLocations.CityID = tblCities.CityID
WHERE tblLocations.RestID = $Lid
GROUP BY tblLocations.RestID, tblCities.CityName
ORDER BY tblCities.CityName ASC");
echo '<option selected="selected">--Select City--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
ajax_area.php
<?php
require('config.php');
if($_POST['Lid'])
{
//$Lid=$_POST['Lid'];
$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblAreas.AreaName as name
FROM tblLocations INNER JOIN tblAreas ON tblLocations.AreaID = tblAreas.AreaID
WHERE tblLocations.RestID = $Lid AND tblLocations.CityID = $Cid
GROUP BY tblLocations.RestID, tblAreas.AreaName
ORDER BY tblAreas.AreaName ASC");
echo '<option selected="selected">--Select Area--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
It was these two lines in the ajax-city.php file.
"SELECT tblLocations.CityId as Cid, tblCities.CityName as name
And
echo '<option value="'.$row['Cid'].'">'.$row['name'].'</option>';