So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>
Related
So, I wanna change, using values from a comboBox, another comboBox values (from database MYSQL ). Don't know where the problem is but thinking about that function.
Sorry for my english btw, isn't my native language.
Here are my dropdown lists in HTML:
<select name="Discipline" id="DisciplineList">
<?php include "combo1.php";
?>
</select>
</div>
<div class="alegere2">
<?php echo "Alegeti lectia:" ;
?>
<select name="lectie" id="lectieList">
</select>
Here is the code that I use to fill the second dropdown list using the values from the first one:
< script type="text/javascript">
$(document).on("change","#DisciplineList",function(){
var val = $(this).val();
$.ajax({
url: "combo2.php",
data: {Discipline:val},
type: "GET" ,
dataType: "html",
success: function(result){
$("#lectieList").html(result);
}
});
});
< /script>
Here is the first comboBox fill: ( it fills corectly)
<?php
require("db.php");
$results = mysqli_query($db,"SELECT nume,id FROM discipline");
$nr_discipline=mysqli_num_rows($results);
while($nr_discipline > 0){
$row = mysqli_fetch_row($results);
echo '<option value="'.$row[1].'">'.$row[0].'</option>';
$nr_discipline--;
}
?>
Here is the 2nd comboBox code : (isn't working )
<?php
// Connects to your Database
require("db.php");
$id_discipline = $_GET['Discipline'];
$Query= "SELECT nume,id FROM lectii WHERE id_disciplina =2";
$lectie = mysqli_query($db,$Query);
$nr_lectie = mysql_num_rows($lectie);
while ($nr_lectie > 0) {
$row = mysql_fetch_row($lectie);
echo '<option value="'.$row[1].'">'.$row[0].'</option>';
$nr_lectie--;
}
?>
I don't know where is the problem. It looks like the function is not working at all.
$("#lectie").html(result);
here lectie is class not id replace lectie by lectieList that is the id
I am new here and newbie learner. I've checked some similar questions like this but could not get them to work.
What I am trying to achieve is, querying my database, retrieve list of accounts, then jquery function sends a query to ajaxtest2.php file for each of the account to retrieve account information and shows it in a html table.
Main problem is, table is populating with information of the last account in the database instead of all accounts.
I am getting this output at the moment:
`3459 1459 3459 1459`
Your help will be much appreciated.
Thank yoU :)
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
?>
<script type="text/javascript">
$(document).ready(function() {
$(window).load(function() {
var numValue = <?php echo $var; ?>;
$.getJSON("ajaxtest2.php", {number: numValue}, function(data){
var trHTML = '';
$.each(data, function () {
trHTML += '<td>' + data.bal + '</td><td>' + data.eq + '</td>';
});
$('#location').append(trHTML);
});
}); `
});
</script>
<table id="location" border='1'>
</table>
<?php
}
The below is the response from ajaxtest2.php
echo json_encode(array("bal" => "$balance", "eq" => "$equity"));
?>
Make sure that you have table rows when you generate the cells.
trHTML += '<tr><td>' + data.bal + '</td><td>' + data.eq + '</td></tr>';
Else your cells will always append to the right of the previous cell without changing rows
Also, the your code could all be done using PHP only (no js)
Here's how:
<?php
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
?>
<table id="location" border='1'>
<?php
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
//your ajaxtest2.php functionnalities go here
//let's say $accBalance and $accEquity contain the information you wanted about that specific row
echo '<tr><td>'.$accBalance.'</td><td>'.$accEquity.'</td></tr>';
}
?>
</table>
And there you have your populated table using database values without using JS.
Hoped it helped!
I'm working to try and establish a "safe" dynamic form using php/jquery. I am trying to figure out how to encode a query result in the URL, but also being able to display the query correctly in the browser. Ive tried wrapping a urlencode around the data in each of the for loops but it outputs the encoded data and disables the ability to populate the second drop down.
<!-- Populate First Dropdown -->
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=htmlentities($row["name"])?></option>
<?php endforeach ?>
</select>
<br />
<!-- Populate Second Dropdown -->
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<!-- Jquery to Populate second and Produce image -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#second-choice").change(function() {
var first = $("#first-choice").val();
var sec = $(this).val();
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
});
});
</script>
Here is the getter.php file I use to populate second drop down using above jquery:
$choice = $_GET['choice'];
$sth = $db->prepare("SELECT code FROM sets WHERE name='$choice'");
$sth->execute();
$choicecode = $sth->fetchColumn();
$stmt = $db->prepare("SELECT * FROM cards WHERE code='$choicecode'");
$stmt->execute();
$data2 = $stmt->fetchAll();
?>
<?php foreach ($data2 as $row): ?>
<option><?=$row["cardname"]?></option>
<?php endforeach ?>
Basically I want to encode the data that goes in the drop downs because they contain spaces and apostrophes. How can I still do this while at the same time output them correctly?
urlencode should be used when you're constructing the query parameters in a URL. When you're putting text into HTML, you should use htmlentities. Also, use the ID column as the value in your options.
<?php foreach ($data as $row): ?>
<option value="<?=$row["id"]?>"><?= htmlentities($row["name"]) ?></option>
<?php endforeach ?>
Also, you should use parametrized queries to prevent SQL injection and avoid other problems when constructing the query if it contains special characters:
$stmt = $db->prepare("SELECT * FROM cards
WHERE code = (SELECT code FROM sets WHERE id = :id)");
$stmt->execute(array(':id' => $_GET['choice']));
$data2 = $stmt->fetchAll();
I'm fairly new to PHP and MySQL, have a little experience with jQuery and almost no experience with JSON, just to give you some background. I am trying to implement cascading dropdowns in my form.
I have two tables:
|city|
|city_id INT| - PK
|city VARCHAR (45)|
|state_state_id INT | - FK
|state|
|state_id INT| - PK
|state VARCHAR (25)|
Here's my form:
State:<br />
<select name="state" id="stateName">
<?php foreach($rows as $row): ?>
<option value="<?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>"><?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>
</option>
<?php endforeach; ?>
</select>
<br /><br />
City:<br />
<select name="city" id="cityName"></select>
<input type="submit" name="work_order_submit" id="" value="Add Work Order" />
I populate the State dropdown with this query:
$query = "SELECT * FROM state WHERE 1 ORDER BY state";
try{
$stmt = $db->prepare($query);
$stmt->execute();
}catch(PDOException $ex){
//On production remove getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
Here's the jQuery I've created to run the JSON and populate the City dropdown with the cascaded values from the state dropdown when a state is selected:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName:$('#stateName').val()},
function(data){
var select = $('#cityName');
var options = select.prop('options');
$('option', select).remove();
$.each(data, function(index, array){
options[options.length] = new Option(array['city']);
});
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
And here's the code in the state-names.php file (I connect to the database before this code):
$rows = array();
if(isset($_GET['stateName'])){
$query = "SELECT city FROM city INNER JOIN state ON city.state_state_id = state.state_id WHERE state = :state ORDER BY city";
$query_params = array(":state" => $_GET['stateName']);
try{
$stmt = $pdo->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
//On production remove .getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
Nothing happens when I select the state in the form. I don't even get an error. I've tested the SQL and it runs fine and retrieves the values that I want, but for some reason that I can't figure out, the values aren't being cascaded into the City dropdown.
Any help is very much appreciated.
EDIT: As I'm doing more debugging and realizing a few things, this is what I've found so far. The JSON comes in like this:
[{"city":"Salt Lake City"},{"city":"Toole"},{"city":"Provo"},{"city":"St. George"}]
I now know the JSON is working correctly. When I changed the dropdown selection in the state dropdown to a state that I know had entries for the cities, the city dropdown showed blank 'option' fields for the number of entries that there actually were. So, using the answer below and MANY different tutorials on cascading dropdowns and chained dropdowns, I finally figured it out. I've submitted an answer with the working code.
Can you try:
$.each(data, function(index, array){
// new Option(text [, value, defaultSelected, selected]);
select.add(new Option(array['city'], index), null);
});
??
All of the code above worked except the jQuery function. Well, the jQuery worked for what I told it to do, not for what I really wanted the code TO DO... Big difference.
Here's the working jQuery that populates the city dropdown based on a selection made in the state dropdown:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName: $('#stateName').val()},
function(data){
var html = '<option value="';
var htmlEnd = '</option>';
var options = '';
var select = $('#cityName');
$('option', select).remove();
$.each(data, function(index, array){
options += html + array['city'] + '">' + array['city'] + htmlEnd;
});
$('#cityName').append(options);
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
Before, the code would find the number of entries and the select box would show this number, but the selections were blank. With this code, the number of entries is found, but the values for those entries also show. Hope this helps someone else later.
I've a select populated by a php query, that loads the nicknames of the users logged in a specific div, called “UserList”.
<div id=”UserList” name=”UserList”>
</div>
This select is placed in a php page, “userlist.php”, loaded by jquery. The php query works fine, so I've avoided writing here the db connection.
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
</select>
My problem is that I need to reload only the select and refreshing it when a user clicks the select itself, so new users that enter the page are added by the php query and those that changed page are removed from the list. But whit every event that I tried the jquery loops, instead of activating the reload only once every time a user clicks the form and the first click event not even reload properly the php query.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#UserList").load('userlist.php');
$("#UserList").click(function() {
$("#UserList").load('userlist.php');
evt.preventDefault();
});
});
</script>
Thanks for your help.
I would suggest using AJAX to do this. AJAX allows you to query the web-server with out refreshing the entire page. This example
seems like almost exactly what you want to do.
Edit:
Put this inside your template:
<div id=”UserList” name=”UserList”>
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result))
{
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result);
?>
</select>
</div>
Then Change the Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#User").click(function() {
$("#User").load('userlist.php');
});
});
</script>
And finally change the userlist.php file:
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>