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)
Related
I’m beginner to JS/PHP/MySQL development. I want to populate a select HTML element with table (nearly 4000 Records) from MySQL DB, relevant code is below.
<body onload="jsonload()">
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
</select>
</body>
<script language="javascript" type="text/javascript">
function jsonload()
{
let jsSelBenEmpNo = document.getElementById("BenEmpNo");
let jsBenEmpNoDataAry;
jsSelBenEmpNo.innerHTML = "<option value='-select-'>-Select-</option>";
oReq = new XMLHttpRequest();
oReq.open('POST', "../php/oh-get_BenEmpNo.php", true);
oReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
oReq.onload = function () {
jsBenEmpNoAry = this.responseText.split('|');
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
jsSelBenEmpNo.innerHTML += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
}
oReq.send("parsparm=" + "|");
}
</script>
</html>
---- PHP ---
<?php
$sql = "select EmpNo, EngName from beneficiary";
$ResultSet = "";
require_once("oh-dbcon.php");
if ($result = mysqli_query($db_con, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$ResultSet = $ResultSet . "|" . $row[0] . "~" . $row[1];
};
$ResultSet = $ResultSet . "~OK";
}else
$ResultSet = "ERROR Result (" . mysqli_error($db_con) . ")-(" . $sql . ")";
mysqli_close($db_con);
echo $ResultSet;
?>***
When I used pure JS (XMLHttpRequest) it takes long time (around 50s) to populate the select, during which the page is froze.
But when using HTML embedded PHP code, it is almost instantly populating the select element (below code).
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
<option value = "-Select-">-Select-</option>
<?php
include("ohdadbcon.php");
$sql_phrase_ben = "select EmpNo, EngName from beneficiary";
$qry_result_ben = #mysqli_query($db_con, $sql_phrase_ben);
while ($row_ben = mysqli_fetch_assoc($qry_result_ben))
{
?>
<option value = "<?php echo $row_ben['EmpNo']?>" >
<?php
echo $row_ben['EngName'] . " | " . $row_ben['EmpNo'] ;
?>
</option>
<?php
}
mysqli_free_result($qry_result_ben);
?>
</select>
I want to use JS request only. Is there any other way or workaround for the slowness to this request?, or I’m doing something wrong here?
2 options... Tweak to only modify the DOM once:
let options = '';
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
options += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
jsSelBenEmpNo.innerHTML = options;
OR
You could also potentially generate the select or options list with PHP, and have THAT returned via AJAX. Then all the JS has to do is add/replace a single element in the DOM. This will move the entire loop to the server instead of the browser.
Though as others have mentioned, 4K items in a drop-down is going to be slow (not to mention very hard to use) just due to the size of the list. I would expect machines with low resources to get a bit choppy when the select is opened.
<?php
include ('config.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Platser</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>
</head>
<body>
<div id="glassbox">
<?php
if(isset($_POST['Spara'])){
}
$antal = $mysqli->query("SELECT `Grupp ID` FROM `Elevgrupper` WHERE `Grupp ID`=25");
$num = $antal->num_rows;
$res = $mysqli->query("SELECT `Namn`, `Efternamn` FROM `Elever` WHERE `ID` IN (SELECT `Användar ID` FROM `Elevgrupper` WHERE `Grupp ID` = 25)");
for ($i = 1; $i<=$num; $i++){
$get_coords = mysqli_query($mysqli, "SELECT * FROM coords WHERE id = '" . $i . "'");
$row = $get_coords->fetch_assoc();
$ok = $res->data_seek($i-1);
$row1 = $res->fetch_assoc();
//
$x = $row['x_pos'];
$y = $row['y_pos'];
echo '<div id="e'. $i .'" class="e" style="left:'.$x.'px; top:'.$y.'px;"><p id="p' . $i .'">'. $row1["Namn"] . " " . $row1["Efternamn"] . '</p></div>';
}
?>
</div>
<form action="<?echo $_SERVER['PHP_SELF'];?>">
<input onclick="spara();" type="submit" name="Spara">
</form>
<div id="respond"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
$("#e" + i).draggable({
containment: '#glassbox',
scroll: false
});
}
});
function spara(){
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
var coords=[];
var coord = $("#p" + i).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
});
}
}
</script>
</html>
<?php
if(!$_POST["data"]){
echo "Nothing Sent";
exit;
}
include ('config.php');
$data = json_decode($_POST["data"]);
foreach($data->coords as $item) {
//Extract X number for panel
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
//Extract Y number for panel
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
//escape just-in case
$x_coord = mysqli_real_escape_string($mysqli, $coord_X);
$y_coord = mysqli_real_escape_string($mysqli, $coord_Y);
//Setup Query
$sql = "UPDATE coords SET x_pos = '" . $x_coord . "' WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
$sql = "UPDATE coords SET y_pos = "'. $y_coord .'" WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
}
//Return Success
echo "success";
?>
If I am not mistaken everything except the spara function should work and it's driving me crazy since I don't get even get any error messages, seems like it runs through the entire script without errors and without saving anything.
What I am trying to do is a teacher tool that from a database which contains all students places out benches that you can drag around and move to your choosing so that you can decide seats for everyone without having to do much work as the teacher. And I want the layout to save by pressing a button which runs the function.
I believe this line could be wrong:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response)
Usually I would have something like this:
$.post('updatecoords.php', {data: somevar}, function(response)
Give that a try, assign $.toJSON(order) to a variable and pass it as suggested.
UPDATE:
Based on Domeniks feedback below, you probably just need to do this:
$.post('/updatecoords.php', somevar, function(response)
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 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.