Fill Drop down On select Of Drop down - php

how to fill dropdown values on selection of multiple dropdown.for example i have following Dropdown list.
On select of second dropdown i wants to fill Third Dropdown With Single selection How can i do. ?
My current code for this is as follow.
//CALL FOR SECOND DROPDOWN
$(document).ready(function(){
$('#select4').on('change',function(){
var subcatgoryId = $(this).val();
console.log(subcatgoryId);
if(subcatgoryId){
$.ajax({
type:'POST',
url:'ajax_load_specification.php',
data:{subcatgoryId: subcatgoryId},
success:function(html){
alert(html);
//$('#select5').html(html);
//$('#loading1').css("display","none")
},
error: function (jqXHR, exception) {
alert("Got Some Errore");
}
});
}else{
$('#select5').html('<option value="">Select Category first</option>');
}
});
});
and php code is as follow
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = explode(',', $_POST["subcatgoryId"]);
print_r($_POST["subcatgoryId"]);
foreach ($subcategory as $key => $value)
{
echo $key;
echo "<br>";
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$item." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}

Just Use For Loop And it starts working
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = $_POST["subcatgoryId"];
$len=count($subcategory);
for ($i=0; $i < $len; $i++) {
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$subcategory[$i]." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}

Related

PHP Script running without redirection

I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});

Dynamic selection how fetch 'Specific Cities of Specific State of Specific Country'?

I have the following setup of a dynamic select options for Country, State and City using php and jquery ajax.
But the problem with this setup is, if two or more of the states have the same name, all of their associated cities become the output irrespective of country.
Like the image below (please imagine Canada has a state named California for the sake of this example):
How can I solve this problem, that is how can I get the output of Cities of State California of Country USA?
These are the sections I guess I need to improve. I have been trying a few methods but none of them is working. So I'll really appreciate any help.
The ajax:
$('.action').change(function() {
if ($(this).val() != '') {
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country") {
result = 'state';
} else {
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {
action: action,
query: query
},
success: function(data) {
$('#' + result).html(data);
}
})
}
});
And the php query I have tried:
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output.= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result))
{
$output.= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
This is the full code in case you need to have a look:
index.php
<?php
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$country .= '<option value="' . $row["country"] . '">' . $row["country"] . '</option>';
}
?>
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>
<script>
$(document).ready(function () {
$('.action').change(function () {
if ($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country")
{
result = 'state';
} else
{
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {action: action, query: query},
success: function (data) {
$('#' + result).html(data);
}
})
}
});
});
</script>
And the fetch.php
<?php
if (isset($_POST["action"])) {
$output = '';
if ($_POST["action"] == "country") {
$query = "SELECT state FROM country_state_city WHERE country = '" . $_POST["query"] . "' GROUP BY state";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select State</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["state"] . '">' . $row["state"] . '</option>';
}
}
if ($_POST["action"] == "state") {
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
}
echo $output;
}
?>
You need populate next selects for all filled selects before and build right query for data.
#Example for populate CITY you need to know which are COUNTRY and STATE was selected.
PHP
if(isset($_POST['country']) && $_POST['country'] != ''
&& (!isset($_POST['state']) || $_POST['state'] == '') {
// return STATES for selected COUNTRY
$sql = "SELECT country, state FROM tbl WHERE country = {postCountry}";
}
else if(isset($_POST['country']) && $_POST['country'] != ''
&& isset($_POST['state']) && $_POST['state'] == '') {
// return CITIES for selected COUNTRY and STATE
$sql = "SELECT country, state, city FROM tbl WHERE country = {postCountry} AND state = {postState}";
}
This query
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
can be changed to DISTINCT
$query = "SELECT DISTINCT country FROM country_state_city ORDER BY country ASC";
JQUERY
Is good approach to wrap data into form because it provides easy work with form elements like selects.
$('.action').change(function() {
var formValues = $(this).closest('form').serialize();
$.ajax({
url: "fetch.php",
method: "POST",
data: formValues,
success: function (data) {
$('#' + result).html(data);
}
});
});
You can check DevTools Console on change and XHR request in Network in demo which values are sent in request to PHP.
DEMO JQUERY
Hope this help.
Happy coding

Output of autocomplete populated from mysql tables

My textboxes get autocomplete populated from mysql tables.
I want to display the output list from the textbox into a selectable option instead of an list item.
echo '<li onClick="fill(\''.$result->naam_klant.'\');">'.$result->naam_klant.'</li>';
My code so far:
'<select onClick="fill(\''.$result->naam_klant.'\');"><option value=$result->naam_klant></option></select>';
Can you guys help me with this ?
UPDATE
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT naam_klant FROM overboekingen WHERE naam_klant LIKE '$queryString%' LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.$result->naam_klant.'\');">'.$result->naam_klant.'</li>';
'<select onClick="fill(\''.$result->naam_klant.'\');"><option value=$result->naam_klant></option></select>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
} // There is a queryString.
} else {
echo 'There should be no direct access to this naam_klant script!';
}
}
?>
You don't give enough information, how you is your results structured?
<select onchange="fill(this.value);" onfocus="this.selectedIndex = -1;">
<?
for ($i=0; $i < count(results); $i++) {
$result = results[i];
echo "<option value='{$result->naam_klant}'>option {$result->naam_klant}</option>\r\n";
}
?>
</select>
Update
Since you want a selectable option instead of an list item
if ($query) {
echo '<select onchange="fill(this.value);" onfocus="this.selectedIndex = -1;">\r\n';
while ($result = $query->fetch_object()) {
echo '<option value={$result->naam_klant}>{$result->naam_klant}</option>\r\n';
}
echo '</select>\r\n';
}

How to get data from database and create a dynamic select?

Im trying to create a select which is dynamic, for example if there is 3 item in the database gift, then it will create 3 select with value from the database lecturer. This is the javascript to create the select when the user click the button add.
Now after the user have create 3 select and submit it, if the user wish to edit back the data, how can I do it ?
function addField(area,field,limit)
{
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("select");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
if(document.createElement)
{
var li = document.createElement("li");
var input = document.createElement("select");
var opt = document.createElement("option")
input.id = field;
input.name = field;
opt.value = "NULL";
opt.textContent = "NO LECTURER";
li.id = "li"+last_item;
input.appendChild(opt);
li.appendChild(input)
$(document).ready(function()
{
$.ajax
({
type:"post",
url: "event/data.php",
success: function(data)
{
console.log(data);
$(input).append(data);
}
});
});
field_area.appendChild(li);
}
}
Here example of what I have create,
http://i.imgur.com/je1MchL.png
Here how it works
http://i.imgur.com/c4ICTWt.png
So basically in the database have 5 data, so what im trying to do is in the next page it will automatic create the exact 5 select. How can I do this?
Thanks
Create a function (useful for reuse)
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
and call it:
// $options : return array from DB
$curr = 'some_key';
$select_name = 'my_select';
echo create_select($select_name,$options,$curr);
A complete working example:
<?php
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('effone_db');
$query = mysql_query("SELECT * FROM settings");
while ($row = mysql_fetch_array($query)) {
$options[$row['option']] = $row['option_value'];
}
echo create_select('settings',$options,'100');
?>
Let's assume that $options holds the resulting query.
So what you must do is loop thru the items and echo them inside a <select> tag.
like:
<html>
<body>
<select name='nameUrSelectHere'>
<?php
foreach($options as $option){
echo "<option value='" . $option['column_one'] . "'>" . $option['column_two'] . "</option>" ;
}
?>
</select>
</body>
</html>

Chained dropdown option not pulling previous values through in to query

I have found a example of chained dropdown boxes, however i am struggling to ensure that the 3rd box uses both the previous boxes in showing the required results.
The boxes are intended to show the following,
DROP DOWN BOX 1 = Select a sector
DROP DOWN BOX 2 = Select a Level
DROP DOWN BOX 3 = Select a Qualification
On the last SQL query i have shown a $HELP, i think this is where im having my problems, i think it is loosing the previously stored value in dropdown box 1 when dropdown box 2 is selected.
<?php
//**************************************
// Page load dropdown results //
//**************************************
function getTierOne()
{
$result = mysql_query("SELECT DISTINCT SSA1Text FROM qualifications ORDER BY SSA1Text ASC")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
echo '<option value="'.$tier['SSA1Text'].'">'.$tier['SSA1Text'].'</option>';
}
}
//**************************************
// First selection results //
//**************************************
if($_GET['func'] == "drop_1" && isset($_GET['func'])) {
drop_1($_GET['drop_var']);
}
function drop_1($drop_var)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT Level FROM qualifications WHERE SSA1Text='$drop_var' ORDER BY Level ASC")
or die(mysql_error());
echo '<select name="drop_2" id="drop_2">
<option value=" " disabled="disabled" selected="selected">Choose one</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['Level'].'">'.$drop_2['Level'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_2').hide();
$('#drop_2').change(function(){
$('#wait_2').show();
$('#result_2').hide();
$.get(\"func.php\", {
func: \"drop_2\",
drop_var: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout(\"finishAjax_tier_three('result_2', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
{//**************************************
// Second selection results //
//**************************************
if($_GET['func'] == "drop_2" && isset($_GET['func'])) {
drop_2($_GET['drop_var']);
}
function drop_2($drop_var)
{
include_once('db.php');
$result = mysql_query("SELECT * FROM qualifications WHERE Level='$drop_var' AND SSA1Text='$HELP'")
or die(mysql_error());
echo '<select name="drop_3" id="drop_3">
<option value=" " disabled="disabled" selected="selected">Choose one</option>';
while($drop_3 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_3['Title'].'">'.$drop_3['Title'].'</option>';
}
echo '</select> ';
echo '<input type="submit" name="submit" value="Submit" />';
}
?>
Any help would be much appreciated.
You could pass both select variables to drop_2 function?
function drop_2($drop_var1, $drop_var2 == null) {
if ($drop_var2 !== null) {
$sqlSnipet = " AND SSA1Text='$drop_var2'"
}
$result =
mysql_query(
"SELECT *
FROM qualifications
WHERE Level='$drop_var' " .
$sqlSnipet
) or die(mysql_error());
}

Categories