I'm using PHP and JS to get data from SQL table then populate the result into a dropdown list.
My code is working fine but I'm having a problem using the return output as an array for JS.
In my PHP part of the code, I'm formatting the output into JSON encode'
echo $js_array = json_encode($Unit_tenants);
// output is ["1","2","3"]
Now I want to use the return value of this output with JS to populate those values into a dropdown list with values 1,2,3
My JS code
<script>
$(document).ready(function(){
$('#ddlUnitNo').change(function(){
//Selected value
var inputValue = $(this).val();
//Ajax for calling php function
$.post('list.php', { dropdownValue: inputValue }, function(data){
//do after submission operation in DOM
var select = document.getElementById("selectNumber");
var options = data;
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
});
});
});
</script>
The problem is in var options = data because this is being recognized as a string rather than an array with multiple values. any idea how to fix this?
Javascript wont accept the php array as an array. You need to convert it to an array, or in this case a JSON object.
Try the following:
in php:
return json_encode($data);
in javascript:
var options = JSON.parse(data);
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
Try this, the PHP way
<?php $js_array = ["1","2","3"]; ?>
<select name="someName" onChange="">
<option value="" selected>Select One</option>
<?php for($k=0, $< count($js_array); $k++){ ?>
<option value="<?php echo($js_array[$k] ?>"><?php echo($js_array[$k] ?></option>
<?php } ?>
</select>
Related
This is a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. How do I display its other columns 'Option_1 to Option_10' (I assumed the maximum options are 10), depending on the 'answer_type' column when it's clicked in real time without refreshing the page? Like if it the 'answer_type' is checkbox it will display it as checkbox and if it's radiobutton it will display radiobuttons. Here's my code of displaying the 'question_title' in the dropdown
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<b id='labelquestion_dropdown".$i."'>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
And here's my database table.
Do some thing like this.
<script>
$.ajax({
url:'ajax.php?id=<?php $row['id']; ?>',
success:function(data){
if(data){
// do what ever you want to do
}
}
});
</script>
on AJAX.php
First you get record against this id that you send in ajax url.
prepare your desired result
Use Ajax Technology then do this in your JS
$(document).on('change','.dynamic-qst',function(){
// ajax question possible answers or rather ajax your database where id = question id
/* $.ajax({
url: 'getPossibleAnswers.php',
data: {id: $(this).val()},
success: function(response){
//insert the var output = '';
// to $('#possible-ans').html(output);
}
}) */
// assuming we had successfully ajax it and the response is
// for question 1 example
var response2 = {'answer_type':'checkbox', 'option_1':'Cellphone', 'option_2':'Computer', 'option_3':'Laptop', 'option_4':'', 'option_5':'', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
// for question 2 example
var response = {'answer_type':'radio', 'option_1':'Sushi', 'option_2':'Maki', 'option_3':'Sashimi', 'option_4':'Teriyaki', 'option_5':'Misono', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
var output = '', x;
for(x = 1; x <= 10 ; x++)
{
var cur_ans = eval("response.option_" + x);
if(response.answer_type == 'checkbox')
{
if(cur_ans != '')
{
output += '<input type="checkbox" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
else if(response.answer_type == 'radio')
{
if(cur_ans != '')
{
output += '<input type="radio" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
}
$('#possible-ans').html(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dynamic-qst">
<option value selected disabled>-- Select One --</option>
<option value="1">What gadget do you usually use?</option>
<option value="2">What is your favorite food?</option>
</select>
<div id="possible-ans"></div>
I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
i am trying to create a dynamic dropdown menu for my website to add address like state, city, area and postcode. i am using code is working when i try one by one preview in live browser but it does not work when i try to use java-script its not show the data in dropdown menucan you plese tell me where i am making mistake
it is index.php
<head>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/scripts.js" type="text/javascript"></script>
<body>
<h1>address</h1>
<hr/>
<label>please select state</label>
<select id="slctstate"></select>
<br />
<br />
<label>please select city</label>
<select id="slctcity"></select>
</body>
</head>
it is script.js
$(document).ready(function() {
$.getJSON("get_stat.php", success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#sltstate").append(options);
});
$("#slctstate").change(function(){
$.getJSON("get_city.php?state=" +$(this).value(), success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctcity").append(options);
});
});
});
it is get_state.php
<?php
require "Connections/dbopen.php";
$query = "SELECT state_name FROM states";
$data = mysqli_query($conn, $query);
$states = array();
while ($row = mysqli_fetch_array($data))
{
array_push($states, $row["state_name"]);
}
echo json_encode($states);
require "Connections/dbclose.php";
?>
and hers is get_city.php
<?php
require "Connections/dbopen.php";
if(isset($_GET["$state"]));
{
$state = $_GET["state"];
$query = "SELECT city_name FROM city
INNER JOIN states ON
city.state_id=states.state_id
WHERE state_name LIKE '{$state}'";
$data = mysqli_query($conn, $query);
$city = array();
while ($row = mysqli_fetch_array($data))
{
array_push($city, $row["city_name"]);
}
echo json_encode($city);
require "Connections/dbclose.php";
}
?>
but at the final step i did not get any value in my drop down can any one please help me thanks
You might want to make the following changes:
change lenght to length
change success = function(data) to function(data)
change isset($_GET["$state"]) to isset($_GET["state"])
refer to http://php.net/manual/en/pdostatement.fetch.php for fetching data in an easier way(optional if the first 3 changes dont work)
I have two dropdown lists as a part of a form I'm creating, both of which have options that are being pulled from a mysql database. I would like the options in the second dropdown to change based on the selection in the first dropdown. I know how to do this using Javascript when the second list is static, but I would like both dropdowns to dynamically pull from the database. Below is the HTML and Javascript I'm currently using. Any ideas would be great.
HTML:
<form>
<label for="org_name">Organization Name:</label>
<select id="org_name" name="org_name" onchange="configureDropDownLists(this,'submitter_name')">
<option value="empty"> </option>
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$query = "SELECT * FROM Table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<option value='" . $row['org_name'] . "'>" . $row['org_name'] . "</option>";
}
mysql_close();
?>
</select>
<label for="submitter_name">Request Submitted By:</label>
<select id="submitter_name" name="submitter_name">
<option value="empty"> </option>
</select>
<input type="Submit" value="Submit">
</form>
Javascript:
function configureDropDownLists(org_name,submitter_name) {
var org = new Array('Submitter 1', 'Submitter 2');
switch (org_name.value) {
case 'org':
document.getElementById(submitter_name).options.length = 1;
for (i = 0; i < org.length; i++) {
createOption(document.getElementById(submitter_name), org[i], org[i]);
}
break;
default:
document.getElementById(submitter_name).options.length = 1;
break;
}
createOption(document.getElementById(submitter_name), 'Other', 'Other');
if (org_name.value === 'empty') {
document.getElementById(submitter_name).options.length = 1;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
As suggested, AJAX was the answer. For anyone curious who comes across this, below is the solution I came up with. I left the HTML unchanged other than removing onchange="configureDropDownLists(this,'submitter_name')" from the first dropdown. Instead of the above Javascript, I used the below AJAX and PHP. Works really nicely.
JQuery:
$(document).ready(function() {
$("#org_name").on("change", function() {
var orgName = document.getElementById("org_name").value;
$.post('admin_list.php', { org: orgName }, function(result) {
$('#submitter_name').html(result);
}
);
});
});
and the referenced PHP page:
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$org_name = $_REQUEST['org'];
$query = mysql_query("SELECT * FROM Table WHERE user = '$org_name'");
while($row = mysql_fetch_array($query)){
echo "<option>" . $row['admin_first_name'] . " " . $row['admin_last_name'] . "</option>";
}
mysql_close();
?>
Sounds like you need some AJAX to pull your data from the database, format on the server side (JSON will likely be easiest to work with), then use a callback function in Javascript to populate the second drop down based on the JSON data received.
I am trying to populate a drop down list using jquery and ajax.
Here's what my code looks like.
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
</script>
Here's time.php
//some code for connecting to database
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
echo"
<select name='timing' id='timing'>";
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo jason_encode($res);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo "</select>";
?>
This just puts list on time.php into a div time on my page. Is there some way I could grap individual options from the list on time .php and add them to a dropdown list on my page?
Thanks in Advance.
try:
success:function(data)
{
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.YourReturnParam + '</option>';
});
$('#yourDdlID').html(option);
}
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
var jdata=eval('('+data+')');;
var str='';
for(var i=0;i<jdata.length;i++)
{
str.='<option>'+jdata[i]+'</option>';
}
$("#time").html(str);
}
});
});
});
time.php will return like
$res=array('a','b','v')
echo json_encode($res);
It would make it easier if the data variable that's used in the success callback is JSON or an array.
success:function(data)
{
var option = $('#time');
//Remove old options
option.empty();
//It makes it easier if you create an array to store all of the values that you want to
//populate the select tag with. I'm not sure if the data that's returned is in the form of an array or not
var newOptions = {'key1': 'value1','key2': 'value2', 'key3': 'value3'};
//Loop thru and change each option tag
$.each(newOptions, function(key, value) {
option.append($('<option></option>').attr('value', value).text(key));
});
}
And the html might look something like this, I'm guessing?
<select id="time">
<option value="val">Text</option>
<option value="val">More Text</option>
</select>