I am trying to run this tutorial from PHP Jquery cookbook but the First combo box is not populating with country data and it is empty!
I have 4 tables in the database and I have checked them and they are all good!
tables are: Country, States, Towns, and Towninfo
In my html I have:
<html>
<head>
</head>
<body>
<ul>
<li>
<strong>Country</strong>
<select id="countryList">
<option value="">select</option>
</select>
</li>
<li>
<strong>State</strong>
<select id="stateList">
<option value="">select</option>
</select>
</li>
<li>
<strong>Town</strong>
<select id="townList">
<option value="">select</option>
</select>
</li>
</ul>
<p id="information"></p>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('select').change(getList);
getList();
function getList()
{
var url, target;
var id = $(this).attr('id');
var selectedValue = $(this).val();
switch (id)
{
case 'countryList':
if(selectedValue == '') return;
url = 'results.php?find=states&id='+ selectedValue;
target = 'stateList';
break;
case 'stateList':
if($(this).val() == '') return;
url = 'results.php?find=towns&id='+ selectedValue;
target = 'townList';
break;
case 'townList':
if($(this).val() == '') return;
url = 'results.php?find=information&id='+ selectedValue;
target = 'information';
break;
default:
url = 'results.php?find=country';
target = 'countryList';
}
$.get(
url,
{ },
function(data)
{
$('#'+target).html(data);
}
)
}
});
</script>
</body>
</html>
and in the php file I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$find = $_GET['find'];
switch ($find)
{
case 'country':
$query = 'SELECT id, countryName FROM country';
break;
case 'states':
$query = 'SELECT id, stateName FROM states WHERE countryId='.$_GET['id'];
break;
case 'towns':
$query = 'SELECT id, townName FROM towns WHERE stateId='.$_GET['id'];
break;
case 'information':
$query = 'SELECT id, description FROM towninfo WHERE townId='.$_GET['id'] .' LIMIT 1';
break;
}
if ($mysqli->query($query))
{
$result = $mysqli->query($query);
if($find == 'information')
{
if($result->num_rows > 0)
{
$row = $result->fetch_array();
echo $row[1];
}
else
{
echo 'No Information found';
}
}
else
{
?>
<option value="">select</option>
<?php
while($row = $result->fetch_array())
{
?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?> </option>
<?php
}
}
}
?>
According to book the first combobox must be populated after the page has been loaded but the I do not know why it is empty! can you please let me know why this is happening!
Calling:
getList();
after your page loaded won't work as it does not have right context of value "this".
You can try to use:
$('select').trigger("change");
instead of getList(); for first time loading
or another way to try:
$(document).ready(function(){
$('select').change(getList);
getList.call($('select'));
function getList(){...}
}
this should set the right context.(but I'm not 100% sure if it will work, as haven't tried to make fiddle.)
Related
I have created 2 drop down menus where the second one should be reacting to the selection of the first.
I have tested both MySQL querys and the work without any problem. For some reason it seems that page getter.php is not 'activated'. Any suggestions?
mainpage
<?php
require_once('includes/db_connect.php');
echo '<select id="first-choice">
<option>Please choose here first</option>';
$sql_lev = "SELECT
id,
klantnaam
FROM adressen
ORDER BY klantnaam ASC ";
if(!$res_lev = mysqli_query($mysqli, $sql_lev)) { include('includes/error_database.php'); die; }
while($row_lev = mysqli_fetch_array($res_lev)) {
echo '<option value="'.$row_lev['id'].'">'.$row_lev['klantnaam'].'</option>';
}
echo '
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>';
?>
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val());
});
</script>
getter.php
<?php
require_once('includes/db_connect.php');
$choice = mysqli_real_escape_string($mysqli, $_GET['choice']);
echo '<option value="">Choose here now</option>';
$sql_cnt = "SELECT
id,
naam
FROM contactpersoon
WHERE klant_id = ".$choice."
ORDER BY naam ASC ";
if(!$res_cnt = mysqli_query($mysqli, $sql_cnt)) { include('includes/error_database.php'); die; }
while($row_cnt = mysqli_fetch_array($res_cnt)) {
echo '<option value="'.$row_cnt['id'].'">'.$row_cnt['naam'].'</option>';
}
?>
Use for Seleted object with $("#first-choice option:selected")
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice option:selected").val());
});
</script>
I have this select , i wanna save each value after change , save it and use in other select
This is my code :
<?
$sql = "SELECT * FROM championnat ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="nom_championnat" id="nom_championnat" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option value=" <?php echo $r['idChampionnat']?>" name="nom_championnat" selected >
<?php echo $r['nomChampionnat'] ?></option>
<?php
}
}
}
?>
</select>
</div>
I need the variable $r['idChampionnat'] to save it in each select and use it in this requete , how can it asve and put it in that requete sql ????
<?php
$sql = "SELECT * FROM equipe where idChampionnat=???? ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="equipe1" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option required value=" <?php echo $r['nomEquipe']?>" name="equipe1" selected ><?php echo $r['nomEquipe'] ?>
</option>
<?php
}
}
}
?>
</select>
just to clear it ,
You need to use jQuery to fire an AJAX call when the first box is selected.
Its been a while since I've done this but this should give you some idea. I took some code from here and here as example
Say your html looks like this
<select id="nom_championnat">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="equipe1"></select>
then you need to tell jquery what to do when nom_championnat changes selection
$('#nom_championnat').change(function() {
var data = "";
$.ajax({
type:"POST",
url : "queryfile.php",
data : "value="+$(this).val(),
async: false,
success : function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var string = data.message.split(",");
var array = string.filter(function(e){return e;});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
and then you need a queryfile.php to handle the ajax requests, something like
<?php
print_r($_POST);
$value = $_POST["value"];
$sql = "select where {$value} ..."
$result = execute($sql);
echo $result;
?>
I have 3 select drop downs which I want when the first one selected, the second shows up, and when the second is selected, the third one shows up, by using if(isset($_post[first_one])) and for the third one using if(isset($_post[second_one]))
SQL:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM sp_meeting_log ";
$result1 = $conn->query($sql);
PHP/HTML:
<div style="position:absolute; top:300px; left:500px;">
<form method="post">
<p>Choose:</p>
<!--Get all orgs ,forums ,Users data available for admin-->
//select the first
<select style="display:inline-block;" name="org">
<option value="All Orgs">All Orgs</option>
//first drop down info release
<?php
if ($result1->num_rows > 0) {
echo "<table><tr><th>orgID</th><th>orgName</th></tr>";
// output data of each row
while($row = $result1->fetch_assoc()) {
echo "<option>" .$row["orgID"]." /".$row["orgName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</select>
<select style="display:inline-block;" name="forum">
<option value="forum1"><h5>All Forums</h5></option>
<?php
// if the first dropdown post set
if(isset($_POST['org'])){
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
echo "<table><tr><th>forumID</th><th>forumName</th></tr>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option>".$row["forumID"]." / ".$row["forumName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
</select>
//select the second
<select style="display:inline-block;" name="user">
<option><h5>All Users</h5></option>
<?php
// if the second drop down is set
if(isset($_POST['forum'])){
$result3 = $conn->query($sql);
if ($result3->num_rows > 0) {
echo "<table><tr><th>userID</th><th>username</th></tr>";
// output data of each row
while($row = $result3->fetch_assoc()) {
echo "<option>".$row["userID"]." / ".$row["username"]. "</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
Essentially this is what the idea is. You want page one to just fetch from page two and post the result back to page one into the correct spots:
page1.php
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form>
<label>Org
<select id="org" name="org">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<!-- This is where the forum html will drop into after ajax runs -->
<div id="forum"></div>
<!-- This is where the user html will drop into after ajax runs -->
<div id="user"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
// On change of a select menu
$(this).on('change','select',function(e){
// Assign selection
var thisSelect = $(this);
// Get the id name, this will tell page two
// what it's receiving
var sendType = thisSelect.attr('id');
// Get the actual value of the selection
var sendVal = thisSelect.val();
// Create essentially a POST
var sendData = { field: sendType, value: sendVal };
$.ajax({
// Send to page 2
url : '/page2.php',
// Use post method
type: "POST",
// Use post data from above
data : sendData,
// This is what will run on success
success:function(response){
// Parse the json coming back for placement
var jSon = JSON.parse(response);
// Save the correct html into the correct drop spot
$('#'+jSon.type).html(jSon.html);
},
error: function(response){
console.log(response);
}
});
});
});
</script>
page2.php
if(!empty($_POST)) {
$data = '';
ob_start();
if(isset($_POST['field'])) {
if($_POST['field'] == 'org') {
$type = 'forum';
?>
<label>Forum
<select id="forum" name="forum">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php
}
elseif($_POST['field'] == 'forum') {
$type = 'user';
?>
<label>user
<select id="user" name="user">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php }
$data = ob_get_contents();
ob_end_clean();
die(json_encode(array('type'=>$type,'html'=>$data)));
}
die(json_encode(array('type'=>'error','html'=>false)));
}
My code works fine here http://jsfiddle.net/qv94t/7/. But when the option value is came from by php the function is not working properly. I used ajax for generating the option value, but it has also the same error if I echo the option value in the same page and not using ajax.
Why is that? Help please
My ajax
getajax.php
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option class="eachop" value ="<?php echo $row['item'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
And here's my full code, I forgot to add my ajax and dropdown. Someone help please?
ajax.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<input list="languages" id="none"></input>
<datalist id="languages" name="options">
<option value=""></option>
</datalist>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<input type="submit" name="submit" value="Submit" />
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#languages').html(data);
}
});
});
</script>
<script>
var validOptions = [];
$("option").each(function () {
validOptions.push($(this).val())
});
previousValue = "";
console.log(validOptions)
$('#none').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function () {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
</script>
you must echo the value then only, ajax get the value and displayed use below code....
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
echo "<option class=\"eachop\" value =\"".$row['item']."\">".$row['item']."</option>";
}
}
?>
I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!
I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?
Here is my code:
<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
}
?>
</select>
</p>
<select>
<option value="select">Please Select From The List</option>
<option id="result"></option>
</select>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCar').change(function()
{
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
In the PHP result I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$resultStr = '';
$query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$resultStr.= '<option value="'.$row['id'].'">'.$row['model'].'</option>';
}
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
You should edit your script into this..
<select id="result">
<option value="select">Please Select From The List</option>
</select>
You are setting $('#result').html(data); in the main file.
result should be the id of the HTML select element, you used it as id for the an option element.
(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)