The tables in test.html are getting create dynamically on a button click add event. The var i is further up in the script.
The html runs and and allows me to select a value from service selection (The selection in the first drop down should simply return a 0,1,2). The value of the selection is passed onto support/descriptions.php via a post, a mysql query is made and I hope to return the result array back to the selection called description. I currently get no values on the alert of the array or vales back to the second selection, but I get no errors either. Do you see anything in the php file preventing the array from getting filled? What is the reason the div for the second drop down is not getting filled either?
The second alert returns a message with the following:
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
test.html
$(document).on('change', '.service', function () {
var element = $(this);
var I = element.attr("id");
$.post("support/descriptions.php", {
id: $(this).val()
},
function (data) {
var response = (data).split(";", 2);
alert(response[0]);
alert(response[1]);
$("#descript" + I).html(response[1]);
});
return false;
});
<table>
<th>Catagory</th>
<th>Select Item</th>
<tr>
<td>
<select class ="service" name="service' + i + '" id="' + i + '">
<option value="0">Select One</option>
<option value="1">Hardscape</option>
<option value="2">Plants</option>
</select>
</td>
<td>
<select name="description' + i + '" id="' + i + '"><div id="descript' + i + '"></div></select>
</td>
</tr>
</table>
descriptions.php
<?php
include('db_connection.php');
$id = $_POST['id'];
if ($id == 1){
$result = mysql_query("SELECT Distinct description FROM hardscape");
}
if($id == 2){
$result = mysql_query("SELECT Distinct description FROM plants");
}
$options = '<option value="Select One">Select One</option>';
while($row = mysql_fetch_array($result)) {
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';
}
echo $id .";".$options.";";
?>
UPDATE -
My issue with the array not getting populated is because I was using ";" as a parse. I found that my data had ";" in them so for testing I changed
echo $id .";".$options.";";
to
echo $id ."~".$options."~";
I also change my div from the inside to the outside
<select name="description' + i + '" id="' + i + '"><div id="descript' + i + '"></div></select>
to
<div id="descript' + i + '"><select name="description' + i + '" id="' + i + '"></select></div>
Last but not least I had to change my php file to the following to rebuild the whole selection:
$options = '<select><option value="Select One">Select One</option>';
while($row = mysql_fetch_array($result)) {
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';
}
$options .='</select>';
echo $options;
$row is an array, to get the field description you have to get it from the array, $row['description']
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';
Related
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 have a select option, after selecting a brand I successfully get/display the brand name but I want also the other values be displayed like price, with or without refreshing the page.
<?php
require_once 'config.php';
echo '<select class="form-control action" name="tran_description" value="<?
php echo $tran_description; ?>" style="background-color:#F0F0F0">';
$sql = mysqli_query($mysqli, 'SELECT * FROM products order by product_id');
while ($row = $sql->fetch_assoc()){
echo '<option id="' . $row['product_id'] . '"';
echo ' value="' . $row['description'] . '" ';
echo ' value="' . $row['price'] . '" ';
if($row['description'] == $tran_description) {
if($row['price'] == $tran_price) {
$tran_price = $row['price'];
echo ' selected="selected"';
}
}
if($row['product_id'] == $row['description']) {
echo ' selected="selected"';
}
echo '>';
echo $row['description'];
echo '</option>';
}
echo '</select>';
?>
I can get the value of the description but the price I couldnt. In one select option representing the brand or description I want also the price value of that brand I selected be assign to a variable so I can do arithmetic operation in the back code without seeing it.Thanks.
You are using wrong HTML structure only the first attribute is being used while the other is being ignored in the DOM .The right way to store multiple values in a single select can be like this:
<select name="">
<option value="{'num_sequence':[0,1,2,3]}">Option one</option>
<option value="{'foo':'bar','one':'two'}">Option two</option>
</select>
In your case it should be like this:
echo '<option id="' . $row['product_id'] . '"';
// echo ' value="{ /"description:/"' . $row['description'] . ', /"price:/"' . $row['price'] . ' }" ';
echo ' value="' .
json_encode(['description'=>$row['description'], 'price'=>$row['price']) .
'">";
Then to get the value you'll do is:
$description = $_POST['NameOfSelectInput']['description'];
$price = $_POST['NameOfSelectInput']['price'];
If you want to get the value in javascript, using jQuery, for example, you could do:
var value = JSON.parse($('#select_id').val()); // use id of your select control
var price = value.price;
var description = value.description;
You should do appropriate error checking...
For more details refer here:
Can an Option in a Select tag carry multiple values?
I am having a trouble with populate a drop-down value from another drop-down with AJAX database. So basically there are Intake and Courses in my form. So, if user choose Intake A, then courses PHP and JQuery will be in Courses option. My problem is now, after i choose Intake A, Courses option doesn't give any value. Can you please help me? Thanks
Here is the AJAX CODE
$(document).ready(function($) {
var list_target_id = 'Courses'; //first select list ID
var list_select_id = 'Iname'; //second select list ID
var initial_target_html = '<option value="">Please select intake...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
//Grab the chosen value on first select list change
var selectvalue = $(this).val();
//alert(selectvalue);
//Display 'loading' status in the target select list
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
//Display initial prompt in target select if blank value selected
$('#'+list_target_id).html(initial_target_html);
} else {
//Make AJAX request, using the selected value as the GET
$.ajax({url: 'CoursesDropdown.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
Here is the PHP side
<?php
include "connect.php";
$selectvalue = mysqli_real_escape_string($con, $_GET['svalue']);
$checkuser = "Select Coursesname from courses Where CoursesIntake ='$selectvalue'";
$result2 = mysqli_query($con, $checkuser);
echo '<option value="">Please select...</option>';
echo $result2;
while ($row = mysqli_fetch_array($result2)) {
//echo '<option value=" . $row["CoursesName"] . "> . $row["CoursesName"] . "</option>"';
//echo '<option value=' . $row['Coursesname'] . '>' . $row['Coursesname'] . '</option>';
echo '<option value="">Please select...</option>';
echo '<option value="">Please select...</option>';
}
mysqli_close($con);
?>
I have a drop down list that is populated by calling another PHP file who's values are taken from a database. The functionality works but I would like to retain the value selected once the onchange form submit happens.
I have had success by using the following for a static lists but not sure how I can get it to work for a dynamic list that is obtained from a database
<option value="company" <?php if($_GET['sort']== 'company') echo 'selected="selected"';?>>Company</option>
Here is the HTML code for the select
<select name="client" id="client" onChange='this.form.submit()'>
<option value="default"></option>
<option value="all">----- ALL CLIENTS -----</option>
<?php
include("sql_clients.php");
?>
And here is part of the the sql_clients.php code
if (sqlsrv_has_rows($result)) {
while( $row = sqlsrv_fetch_array($result))
{
echo ('<option value="' .$row[CompanyName] . '">' . $row['CompanyName'] . "</option>" ."\n" ."\t" ."\t" ."\t" ."\t" ."\t");
}
}
Thanks
Its the same thing, just now instead of one hardcoded value, use the variable:
while( $row = sqlsrv_fetch_array($result))
{
echo '<option value="' .$row['CompanyName'] . '"';
if($_GET['sort']==$row['CompanyName'])
{
echo ' selected="selected"';
}
echo '>' . $row['CompanyName'] . "</option>" ."\n" ."\t" ."\t" ."\t" ."\t" ."\t";
}
Also $row[CompanyName] should be $row['CompanyName']
I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.