The given below is my php code, I want to extract values from database that matches the text inserted by user in text field when clicked on submit button using AJAX.
The given below is the code:
<!doctype html>
<html>
<head>
<title>Bootstrap Table</title>
<link rel="stylesheet" href="bootstrap/bootstrap-4.0.0-alpha.6-dist/css/bootstrap.min.css">
<script src="bootstrap/jquery-3.1.1.min.js"></script>
<script src="bootstrap/bootstrap-4.0.0-alpha.6-dist/js/bootstrap.min.js"></script>
<style>
.container{margin:auto;}
</style>
</head>
<body>
<div class="container">
</div>
<div class='col-sm-3' style='margin-left:10%;'>
<form class='navbar-form' action='' method='POST'>
<div class='input-group'>
<input type='text' class='form-control' placeholder='Search' name='srch-term' id='search_data'>
<div class='input-group-btn'>
<input class='btn btn-search' type='submit' id='search_button' style='cursor:pointer;'>Search</button>
</div>
</div>
</form>
</div>
<div class="result">
</div>
<script id="source" language="javascript" type="text/javascript">
$('#search_button').click(function() {
var search_data = 'input[name=srch-term]'.val();
$.ajax({
type: "POST",
url: 'bootstrap_table_db2.php',
data: {search: search_data},
success: function(result) {
for (var i in result) {
var row = result[i];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
result+= "<tr>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>";
}
$(".result").html(result);
}
});
});
</script>
</body>
</html>
The given below is bootstrap_table_db2.php.
<?php
mysql_connect("localhost", "root", "password") || die(mysql_error());
mysql_select_db("emp") || die(mysql_error());
if(isset($_POST['search']) && !empty($_POST['search'])) {
$result2 = mysql_query("SELECT * FROM employee WHERE Employee_name = 'search'");
$data2 = array();
while ( $row = mysql_fetch_row($result2) ) {
$data2[] = $row;
}
echo json_encode( $data2 );
}
?>
Related
I have made a simple php and jquery based program. In which when a page is open then I want to show all category data first and All is selected. And then when change category by dropdown then data will be display according to selected Category.
But using this change function of jquery how to do that.
Two files:
index.php file
<?php
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#select_category").change(function(){
var catid = $("#select_category option:selected").val();
$.ajax({
type : "post",
url : "product.php",
data: { id:catid },
success: function (response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>"+
"<th>Product Name</th>"+
"<th>Category</th>"+
"<th>Publish</th>"+
"</tr>";
$.each(getres.data , function (key,value){
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results+= "</table>";
$(".result-container").html(results);
}
});
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['cat_id'] ?>"><?php echo $row['cat_name'] ?></option>
<?php } ?>
</select><br><br><br>
<div class="result-container">
</div>
</body>
</html>
product.php file
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$cat_id = $_POST['id'];
$query = "SELECT p.name AS product_name,CASE WHEN p.publish='yes' THEN '+' ELSE '-' END AS publish,c.cat_name AS categoryFROM product p LEFT JOIN category c ON c.cat_id = p.category";
if(!empty($cat_id)){
$query = $query. 'WHERE p.category='.$cat_id;
}
$sql = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$result=array('data'=>$rows);
echo json_encode($result);
You can do that by calling same ajax code on page load with empty category id.
<?php
$db = mysql_connect('localhost', 'root', 'testing') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxCall(catid = '') {
$.ajax({
type: "post",
url: "product.php",
data: { id: catid },
success: function(response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>" +
"<th>Product Name</th>" +
"<th>Category</th>" +
"<th>Publish</th>" +
"</tr>";
$.each(getres.data, function(key, value) {
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results += "</table>";
$(".result-container").html(results);
}
});
}
$(document).ready(function() {
ajaxCall();
$("#select_category").change(function() {
var catid = $("#select_category option:selected").val();
ajaxCall(catid);
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['cat_id']; ?>">
<?php echo $row['cat_name']; ?>
</option>
<?php } ?>
</select>
<br>
<br>
<br>
<div class="result-container"></div>
</body>
</html>
I am using ajax, to simply update the DB..The problem is that after update, I use a alert to display the output. However when I click the alert box,The entire page reloads. Is there any way to avoid it??
First Up(trailnew.php)- A select drop down button with three button.
When I choose the select drop down button and click edit button
Second- I get a form from aanew.php(with some other things)
Third-Validation of this form is done in aanew.php
Target-I want the success result to be viewed in trailnew.php, without reloads.
Any alternative ideas is highly welcomed..This is new to me..Thanks..
Here is the code.
Trailnew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
debug: false,
rules: {
plid:"required",
},
messages: {
plid: "Please select a pack name id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "aanew.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div class="result3"></div>
Packing List
</br>
<form id="form1" name="form1" action="" method="post">
<?php
echo '<select name="plid" id="plid">';
echo '<option value="" selected="selected">--Select the Pack Name--</option>';
$tempholder = array();
$sql="SELECT CONCAT( p.pl_no, '_', DATE_FORMAT( p.pl_dt, '%d/%m/%Y' ) , '_', g.acname ) AS plname, g.gl_id,p.pl_no,p.pl_dt,p.no_box,p.pl_id,g.acname FROM packlist p, glmast g WHERE g.gl_id = p.gl_id ORDER BY pl_dt DESC , pl_no DESC LIMIT 30";
$query = mysql_query($sql) or die(mysql_error());
$nr = mysql_num_rows($query);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($query);
if (!in_array($r['plname'], $tempholder)){
$tempholder[$i] = $r['plname'];
echo "<option value='$r[pl_id]'>".$r["plname"]."</option>";
}
}
echo '</select>';
?><br/>
<input type="submit" name="delete" value="Delete"/><br/>
<input type="submit" name="edit" id="edit" value="Edit"/><br/>
</form>
<form>
<input type="submit" name="new" id="new" class="new" value="New" /><br/>
</form>
<?php
$e=isset($_POST['form2']) && $_POST['form2'];
if($e)
{
echo "Done";
}
?>
<div id="result1"></div>
</body>
</html>
aanew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$("#form2").validate({
debug: false,
rules: {
plnoedit:"required",
pldtedit:"required",
noboxedit:"required",
glidedit:"required",
},
messages: {
plnoedit: "Please select a pack list id..",
pldtedit: "Please select a item id id..",
noboxedit: "Please select a quantity id..",
glidedit: "Please select a value id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "trailnew.php",
data: $('#form2').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
</script>
</head>
<body>
<div id="#result1"></div>
<?php
$e=isset($_POST['plid']) && $_POST['plid'];
$f=isset($_POST['edit']) && $_POST['edit'];
if($e&&$f)
{
$id=$_POST['plid'];
$query5=mysql_query("SELECT g.gl_id, p.pl_no, p.pl_dt, p.no_box, p.pl_id,g.acname
FROM packlist p, glmast g
WHERE g.gl_id = p.gl_id
AND p.pl_id ='".$id."'
LIMIT 0 , 30") or die(mysql_error());
$row=mysql_fetch_array($query5);
$pl_no=$row['pl_no'];
$pl_dt=$row['pl_dt'];
$no_box=$row['no_box'];
$acname=$row['acname'];
?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plnoedit">PackList No
<INPUT type="text" id="plnoedit" name="plnoedit" value= <?php echo $pl_no; ?> /></LABEL><BR><BR>
<input type="hidden" name="myFormsName" value="form5id" id="myFormsName">
<LABEL for="pldtedit">Date
<INPUT type="text" id="pldtedit" name="pldtedit" value= <?php echo $pl_dt; ?> /></LABEL><BR><BR>
<LABEL for="noboxedit">Box No
<INPUT type="text" id="noboxedit" name="noboxedit" value= <?php echo $no_box; ?> /></LABEL><BR><BR>
<LABEL for="glidedit">Party Name
<INPUT type="text" id="glidedit" name="glidedit" value= <?php echo $acname; ?> /></LABEL><BR><BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit"> <INPUT type="reset">
</P>
</form>
<?php
//pagination starts
$id=$_POST['plid'];
$per_page = 4;
$query12=mysql_query("SELECT `pld_id`,`pl_id`, `item_id`, `quantity`, `size`, `potency`, `box` FROM `packlistdtl` WHERE pl_id ='".$id."' GROUP BY `box` ORDER BY `box` desc") or die(mysql_error());
// figure out the total pages in the database
$total_results = mysql_num_rows($query12);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Box</th> <th>Item Name</th> <th>Size</th> <th>Potency</th> <th>Quantity</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
$item_id=mysql_result($query12, $i, 'item_id');
$query13=mysql_query("SELECT `item_name` FROM `itemmast` WHERE item_id ='".$item_id."'") or die(mysql_error());
$row1=mysql_fetch_array($query13);
$item_name=$row1['item_name'];
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($query12, $i, 'box') . '</td>';
echo '<td>' .$item_name. '</td>';
echo '<td>' . mysql_result($query12, $i, 'size') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'potency') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'quantity') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
}
?>
</body>
</html>
Probably need to return false from click handler of link or button to prevent the default action
I am trying to highlight a table row using Jquery's .hover() method.
I have the following code:
var x;
var namen;
window.onload = function(){
x = true;
y = true;
$("submitnieuw").observe('click', addturf);
$("submitdelete").observe('click', verwijderturf);
$("stats").on("click", "tr", select);
setInterval(function (){
jQuery("#recent").load("vandaag.php");
if(x){
jQuery("#stats").load("stats.php");
}
}, 10000);
$("tr").not(':first').hover(
function () {
$(this).addClassName("selected");
},
function () {
$(this).removeClassName("selected");
}
);
alert("test");
};
function select(naam){
//highlight the selected list element
if (y){
var name = naam.findElement('tr').id;
if (name !== ""){
x = false;
y = false;
jQuery.ajax('details.php',{
data: {
'Naam': name,
'door': $("door2").value
},
type: 'post',
success: function(data){
$("stats").innerHTML = data;
},
error: ajaxFailure
});
}
}
else{
x = true;
y = true;
jQuery("#stats").load("stats.php");
jQuery("#recent").load("vandaag.php");
}
}
function verwijderturf() {
var box = document.getElementById("naamverwijder");
var naam = box.options[box.selectedIndex].value;
document.getElementById("naamnieuw").selectedIndex=0;
$("redennieuw").value = "";
jQuery.ajax('server.php',{
data: {
'mode': 'verwijderturf',
'naam': naam,
'door': $("door2").value
},
type: 'post',
success: update,
error: ajaxFailure
});
}
function addturf() {
var box = document.getElementById("naamnieuw");
var naam = box.options[box.selectedIndex].value;
document.getElementById("naamnieuw").selectedIndex=0;
var reden = $("redennieuw").value;
$("redennieuw").value = "";
jQuery.ajax('server.php',{
data: {
'mode': 'addturf',
'naam': naam,
'door': $("door2").value,
'reden': reden
},
type: 'post',
success: update,
error: ajaxFailure
});
}
function update(ajax){
jQuery("#stats").load("stats.php");
jQuery("#recent").load("vandaag.php");
}
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" +
"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
throw exception;
}
}
selected is defined in the css I have included in my index.php.
This is my index.php
<?php
include_once("db.php");
session_start();
if (!isset($_SESSION['uid'])){
header("location:main_login.php");
exit();
}
if (!isset($_SESSION['upass'])){
header("location:main_login.php");
exit();
}
$sql="SELECT * FROM users WHERE Naam='".$_SESSION['uid']."' AND Wachtwoord='".$_SESSION['upass']."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count < 1){
header("location:main_login.php");
exit();
}
?>
<?php
$date = date("y-m-d");
$vandaag = mysql_query("SELECT Type, Naam, Reden, Door FROM turfjes WHERE turfjes.Datum = '" . $date . "'");
$names = mysql_query("SELECT Naam From users");
$names2 = mysql_query("SELECT Naam From users");
$names3 = mysql_query("SELECT Naam From users");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tomaten turfjes pagina | 258</title>
<link rel="stylesheet" type="text/css" href="css/reset.css" media="all" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
<script type="text/javascript" src="js/jquery.js"></script>
<script>
jQuery.noConflict();
</script>
<script src="js/prototype.js" type="text/javascript"> </script>
<script src="js/scriptaculous.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"> </script>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="info">
<div id="recent">
<fieldset>
<legend>Vandaag</legend>
<table border="0">
<tr>
<td>Type</td>
<td>Naam</td>
<td>Reden</td>
<td>Door</td>
<?php
while($a = mysql_fetch_array($vandaag)){
?> <tr>
<td><?php echo($a['Type']);?></td>
<td><?php echo($a['Naam']);?></td>
<td><?php echo($a['Reden']);?></td>
<td><?php echo($a['Door']);?></td>
</tr>
<?php
}
?>
</table>
</fieldset>
</div>
<div id="stats">
<fieldset>
<legend>Turfjesteller</legend>
<table border="0">
<tr>
<td>Naam</td>
<td>Aantal</td>
<td>Gedaan</td>
<td>Resterend</td>
</tr>
<?php
while($r = mysql_fetch_array($names)){
echo("<tr id=".$r['Naam'].">");
?>
<td><?php echo($r['Naam']);?></td>
<?php
$sql="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Adtje'";
$result=mysql_query($sql);
$count=mysql_num_rows($result); //count = adtjes
$sql2="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Turfje'";
$result2=mysql_query($sql2);
$count2=mysql_num_rows($result2); //count2 = turfje
?>
<td><?php echo($count2);?></td>
<td><?php echo($count);?></td>
<td><?php echo($count2-$count);?></td>
</tr>
<?php
}
?>
</table>
</fieldset>
</div>
</div>
<div id="actie">
<div id="nieuw">
<fieldset>
<legend>Nieuwe turfjes</legend>
<label>Naam</label>
<select id = "naamnieuw">
<option value="" selected></option>
<?php
while($r = mysql_fetch_array($names2)){
echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
}
?>
</select>
<br>
<label>Reden</label> <input type="text" name="redennieuw" id="redennieuw"/> <br>
<label>Door</label> <input type="text" name="door" id="door" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>> <br>
<div id = "buttonz"><button type="button" id="submitnieuw">Turfje uitdelen</button></div>
</fieldset>
</div>
<div id="verwijder">
<fieldset>
<legend>Verwijderen turfjes</legend>
<label>Naam</label>
<select id = "naamverwijder">
<option value="" selected></option>
<?php
while($r = mysql_fetch_array($names3)){
echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
}
?>
</select>
<br>
<label>Door</label> <input type="text" name="door" id="door2" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>> <br>
<div id = "buttonz"><button type="button" id="submitdelete">Turfje verwijderen</button></div>
</fieldset>
</div>
<form name="logout" method="post" action="logout.php">
<div id = "buttonz"><input type="submit" name="logout" value="Log uit"></div>
</form>
</div>
</div>
</body>
</html>
The test alert is not executed so I know that my hover is not working. I checked and everything before the hover is executed however and still functional.
I am not quite sure what I am doing wrong.
Can anybody help me please?
My syntax seems to be just fine, according to online checkers.
There's no such thing as addClassName in jQuery, did you mean addClass?
Try this:
$("tr").not(':first').hover(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);
Also, your selector could be "simplified" to $("tr:not:(first)")
It seems (not sure due to your code being php) that you want to apply hover on elements that aren't present on load. If that's the case, you cannot simply do
$("tr").not(':first').hover(
You must use jquery on so that it will be applied to all elements appearing.
To replace a hover by a on, you have to hook the 'mousenter' and 'mouseleave' events :
$('body').on('mousenter', 'tr:not(:first)', function({ ... });
$('body').on('mouseleave', 'tr:not(:first)', function({ ... });
dynamically adds more dropdownlist that is populated with data from MySQL to div on button click.
<div id="dynamicDiv"><p>
sqlconn();
$sql="SELECT column_name FROM table";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
echo "<select type=\"column_name\">";
for($i=0;$i<$num_rows;$i++){
$table = mysql_fetch_array($result);
echo "<option value='" . $table['column_name'] . "'>" . $table['column_name'] . "</option>";
}
echo "</select>";
mysql_close($con);
</div>
<input type="button" value="+ Data" onClick="addInput('dynamicDiv');">
the only method i know is by writing a script but i can't do any php scripting on the script (or i can?). need to query to populate added drop down list.
var counter = 1;
var limit = 15;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "whatever needs to be dynamically input on div";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
is there a workaround to populate the dropdownlist in the script? much appreciated!
You basically have 2 options
Create the HTML for the dropdown list when creating the page and do something like
as in
<script type=...>
var selecthtml='<?php echo $selecthtml; ?>'
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = selecthtml;
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
Or look at AJAX to populate your select.
The former is easier, the latter is cleaner.
**This is the actual way the test goes and Change according to your table and use it . It will work as you expected**
";
echo 'countStud ='.count($arrayData).';';
echo 'stud = '.json_encode($arrayData).';';
echo "";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
divCount =0;
function createDiv()
{
var divTag = document.createElement("div");
var studList ="";
studList += '<select id="BOX_'+divCount+'" name="BOX_'+divCount+'">';
studList += '<option value="">--- Select ---</option>';
for(i=0;i<countStud;i++){
studList += '<option value="'+stud[i].stud_id+'">'+stud[i].stud_name+'</option>';
}
studList += '</select>';
divTag.innerHTML = studList;
document.getElementById('dynamicElements').appendChild(divTag);
divCount++;
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div id="dynamicElements"></div>
<input type="submit" value="Submit" />
</form>
<input type="button" onClick="createDiv()" value="Add"/>
</body>
</html>
I'm trying to populate a third set of radiobuttons as an addition to the following script: http://www.electrictoolbox.com/json-data-jquery-php-radio-buttons/
For some reason I cannot seem to fill the third set with the corresponding data. It just stays blank :(
Calling the populateFruittype() function only gives back [ ], while populateFruitVariety() returns the json data correctly.
getdata.php (DB connection / fetching data)
<?php
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "username";
$password = "password";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE variety = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function populateFruitVariety() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('getdata.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitVariety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
}
function populateFruittype() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
$(function() {
$('input[name=fruitName]').change(function() {
populateFruitVariety();
});
});
$(function() {
$('input[name=fruitVariety]').change(function() {
populateFruittype();
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>
The DB query and content can be found here: http://www.electrictoolbox.com/mysql-example-table/
Just add:
`fruittype` varchar(50) NOT NULL
and fill it with some custom values.
1) DB uddate
ALTER TABLE fruit ADD COLUMN `fruittype` varchar(50) NOT NULL;
UPDATE fruit SET fruittype = 'description' /* WHERE name = 'Apple'*/;
2) code update
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('input[name=fruitName]').change(function() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('test.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<input type="radio" name="fruitVariety" value="' + array['variety'] + '" /><label>' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
});
$('input[name=fruitVariety]').live('click', function() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('test.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<input type="radio" name="fruitType" value="' + array['fruittype'] + '" /><label>' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>