Loading JSON data with jQuery, PHP and MySQL for radio buttons - php

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>

Related

Reset second jquery drop down select box when first is changed

I am using the following script to fetch records from my database and put them into select boxes using jquery, ajax and php. The select boxes are also styled and added features using Select 2
http://ivaynberg.github.io/select2/select-2.1.html#basics
If I select a customer from the first select box and then select a vehicle from the second box this works fine........if I then change my mind and select a different company, the vehicle box stays on the last reg and doesn't revert back to :
<option>Select A Customers Vehicle</option>
If I then click on the vehicle select box I can select the vehicles from the company and the 'ghost vehicle' from the last query vanishes, so it does work, its just when I change the company again I would like it just to reset the vehicle box back to its default again until I select a vehicle.
This is the Main Page :
<script src="js/jquery/jquery.js"></script>
<script src="js/jqueryui/js/jquery-ui.js"></script>
<link href="js/select2/select2.css" rel="stylesheet"/>
<script src="js/select2/select2.js"></script>
<script>
$(document).ready(function() { $("select").select2(); });
</script>
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
if (isset($_SESSION['key'])) {$sessionkey = $_SESSION['key'];}else {$sessionkey = '';}
if ($sessionkey == 'sbhjbKA2bsbhjbKA209bhjbKA2bsbhjbKA209KaXff19u0bsbhjbKA209KaXff19u9Ka'){
include 'connectmysqli.php';
echo '<link rel="stylesheet" href="css/template/template.css" />';
echo '<strong class="pagetitle">Add New Sale</strong>
';
$saleID = rand().rand();
$today = date("Y-m-d");
echo '<form method="post" action="addsalesubmit.php">';
echo '<input type="hidden" value="'.$saleID.'" name="saleID" id="saleID">';
echo '<input type="hidden" value="'.$today.'" name="date" id="date">';
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Select test</title>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
});
});
});
</script>
</head>
<body>
<br>
<select id="customer">
<option>Please Select / Search For A Customer</option>
<?php
$sql = <<<SQL
SELECT *
FROM `customers`
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
while($row = $result->fetch_assoc()){
if ($row['bussinessname'] == ''){$name = $row['title'].' '.$name = $row['firstname'].' '.$name = $row['surname'];}else
{$name = $row['bussinessname'];}
echo '<option value="'.$row['customerID'].'">'.$name.'</option>';
}
echo '</select></p>';
?>
</select>
<br>
<br>
<select id="vehicle">
<option>Select A Customers Vehicle</option>
</select>
</body>
</html>
<?php
}
else
{echo '<h1 style="font-family:Verdana, Geneva, sans-serif; color:red;">Access Denied !</h1>';}
?>
This is the php script that does all the fetching :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['customerId'];
$sql = 'SELECT * FROM vehicles WHERE customerID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'id' => $row['vehicleID'],
'reg' => $row['reg'],
'make' => $row['make'],
'model' => $row['model']
);
}
echo json_encode($json);
?>
On every call of the onchange first empty the second dropdown
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$('#vehicle').html("<option value=''>Select</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
$("select").select2();
});
});
});
</script>
the following is not asked but i have to advice you that there are some additional errors in your code:
echo '</select></p>';
?>
</select>
there are two </select> and one </p> without a starting <p> at the end of your customer select box

Jquery .hover not functioning

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({ ... });

get POST value from Array Elements

I'm having trouble getting POST value from dynamically generated txtinput[] and MultiSelect since they form an array. I read so many articles but I get confuse..
a short form of my code is given below..
Pls help me with best way how I can get array values in the form of a string "value1, value2, value3"
Regards... and Thanks.....
below is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//initially hide the textbox
$("#other_lang").hide();
$('#lang').change(function() {
if($(this).find('option:selected').val() == "Other - specify"){
$("#other_lang").show();
}else{
$("#other_lang").hide();
}
});
$("#other_lang").keyup(function(ev){
var othersOption = $('#lang').find('option:selected');
if(othersOption.val() == "Other - specify")
{
ev.preventDefault();
//change the selected drop down text
$(othersOption).html($("#other_lang").val());
}
});
$('#form_id').submit(function() {
var othersOption = $('#lang').find('option:selected');
if(othersOption.val() == "Other - specify")
{
// replace select value with text field value
othersOption.val($("#other_lang").val());
}
});
});
var counter = 1;
var limit = 3;
var phonefields = "<input name='phoneno[]' id='phoneno[]' class='phoneno' type='text'/>";
function addInput(divName){
if (counter == limit) {
alert("Max. " + counter + " Phone numbers only");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = phonefields;
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form class="form" method="post" name="form" action="">
<label for="langs">Languages:</label><?php dyn_languages() ;?>
<input id="other_lang" name="other_lang" type="text" placeholder="Other lang" /><br /><br /><br />
<label for="phoneno[]">Phone No:</label>
<input id="buttonAsLink" type="button" onClick="addInput('dynamicInput')">
<div id="dynamicInput"><input name='phoneno[]' id='phoneno[]' type='text'/></div>
<input name="submit" type="submit" value="Submit" />
</form>
<?php
//----Dynamic SelectBox for languages
function dyn_languages(){
$langs = array (1 => 'English', 'French', 'German', 'Russian', 'Spanish', 'Other - specify');
echo "<select size='6' name='lang' id='lang' multiple='multiple'>";
foreach ($langs as $value) {
echo (in_array($value,$_POST)) ? '<option value="'.$value.'" selected>'.$value.'</option>\n' : '<option value="'.$value.'">'.$value.'</option>\n';
} echo '</select>';
}//--END Function* --Dynamic SelectBox for languages
//--- POST Action
if(isset($_POST['submit'])){
$phoneno = $_POST['phoneno'];
$langs = $_POST['lang'].",".$_POST['other_lang'];
$sql = "INSERT INTO table(lang, phoneno) VALUES ('$phoneno','$langs')";
echo "<hr />".$sql;
}
//--- END POST Action
?>
</body>
</html>
If I understand correctly, you should try this
$phoneno = implode(', ',$_POST['phoneno']);
http://php.net/manual/en/function.implode.php
I managed to do it with
foreach ($_POST['phoneno'] as $ph) {$phoneno.= $ph.", ";}
foreach ($_POST['lang'] as $lng) {$langs.= $lng.", ";}

Why isnt this ajax live search working

**Updated code as of 3-28
Index.php
<!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>
<title>jQuery Search Demonstration</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".keywords").keyup(function(){
$('#key').html($(this).val());
$('#table').html($('.table:checked').val());
// Do the ajax call
// Get the textbox value: $(this).val()
// Get the radio value: $('.table:checked').val()
/*$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#content").empty()
$.each(data, function(){
$("div#content").append("- <a href='prof.php?pID=" + this.pID + "'>" + this.last + "</a>");
});
}, "json");*/
});
});
</script>
</head>
<body>
Search by:
<input type="radio" name="table" class="table" value="Table 1" />Professor<br />
<input type="radio" name="table" class="table" value="Table 2" />Department<br />
<input type="radio" name="table" class="table" value="Table 3" />Course<br />
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="content">
</div>
</body>
</html>
Search.php
<?php
$link = mysql_connect('##',"##","##");
mysql_select_db("###", $link);
$keywords = mysql_real_escape_string( $_POST["keywords"] );
$query = mysql_query("SELECT pID, lname, fname
FROM Professor
WHERE CONCAT(lname,fname) LIKE '%". $keywords . "%'");
$arr = array();
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "pID" => $row["pID"], "last" => $row["lname"], "first" => $row["fname "] );
}
echo json_encode( $arr );
?>
Sql for each selection:
[Professor]
SELECT pID, lname, fname
FROM Professor
WHERE CONCAT(lname,fname) LIKE '%". $keywords . "%'";
[Department]
SELECT prefix, code
FROM Department
WHERE name LIKE '%". $keywords . "%'";
[course]
SELECT prefix, code
FROM Course
WHERE CONCAT(prefix,course) LIKE '%". $keywords . "%'";
You should change your query like this:
$query = mysql_query("SELECT pID, lname, fname
FROM Professor
WHERE CONCAT(lname,fname) LIKE '%". $keywords . "%'");
Please make sure this these fields in json and javascript are the same:
$arr[] = array( "id" => $row["pID"], "last" => $row["lname"], "first" => $row["fname"] );
$("div#content").append("- <a href='post.php?id=" + this.id + "'>" + this.first + " " + this.last + "</a>");
HTML code:
<!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>
<title>jQuery Search Demonstration</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".keywords").keyup(function(){
getData();
});
$(".table").click(function(){
getData();
});
});
function getData(){
$.post("search.php",
{
keywords: $(".keywords").val(),
table: $('.table:checked').val()
},
function(data){
$("div#content").empty();
var phppage;
switch($('.table:checked').val())
{
case 'professor':
phppage = 'prof';
break;
case 'department':
phppage = 'department';
break;
case 'course':
phppage = 'course';
break;
}
$.each(data, function(){
$("div#content").append("- <a href='" + phppage + ".php?pID=" + this.id + "'>" + this.name + "</a>");
});
},
"json");
}
</script>
</head>
<body>
Search by:
<input type="text" name="search" class="keywords" /><br />
<input type="radio" name="table" class="table" value="professor" checked="checked" /> Professor<br />
<input type="radio" name="table" class="table" value="department" /> Department<br />
<input type="radio" name="table" class="table" value="course" /> Course<br />
<div id="content"></div>
</body>
</html>
PHP code:
<?php
$link = mysql_connect('localhost',"#","#");
mysql_select_db("#", $link);
$arr = array();
$keywords = mysql_real_escape_string( $_POST["keywords"] );
switch ($_POST["table"])
{
case 'professor';
$arr = getProfessor($keywords);
break;
case 'department';
$arr = getDepartment($keywords);
break;
case 'course';
$arr = getCourse($keywords);
break;
}
echo json_encode( $arr );
function getProfessor($keywords){
$arr = array();
$query = mysql_query("SELECT pID, lname, fname
FROM Professor
WHERE CONCAT(lname,fname) LIKE '%". $keywords . "%'");
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "id" => $row["pID"], "name" => $row["fname"] . ' ' . $row["lname"]);
}
return $arr;
}
function getDepartment($keywords){
$arr = array();
$query = mysql_query("SELECT prefix, code
FROM Department
WHERE name LIKE '%". $keywords . "%'");
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "id" => $row["code"], "name" => $row["code"]);
}
return $arr;
}
function getCourse($keywords){
$arr = array();
$query = mysql_query("SELECT prefix, code
FROM Course
WHERE CONCAT(prefix,course) LIKE '%". $keywords . "%'");
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "id" => $row["code"], "name" => $row["code"]);
}
return $arr;
}
?>
It looks like in your javascript you're trying to access the .id and .title properties of the returned json objects but they don't exist from the array you create in php
$arr[] = array( "id" => $row["pID"], "title" => $row["lname"]." ".$row["fname"] );
Does that work?
EDIT:
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#content").empty()
$.each(data, function(){
$("div#content").append("- <a href='post.php?id=" + this.id + "'>" + this.first + " " + this.last + "</a>");
});
});
Looks like that is missing a closing brace to enclose the $.each
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#content").empty()
$.each(data, function(){
$("div#content").append("- <a href='post.php?id=" + this.id + "'>" + this.first + " " + this.last + "</a>");
});
});
});

Problem with Mootools Ajax request and submitting a form

I have a table with content comming from a database. Now i tryed to realize a way to (a) delete rows from the table (b) edit the content of the row "on the fly". (a) is working perfectly (b) makes my head smoking!
Here is the complete Mootools Code:
<script type="text/javascript">
window.addEvent('domready', function() {
var eDit = $('edit_hide');
eDit.slide('hide');
var del = new Request.HTML(
{
url: 'fuss_response.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
eDit.slide('in');
}
});
$$('input.delete').addEvent( 'click', function(e){
e.stop();
var aID = 'delete_', bID = '';
var deleteID = this.getProperty('id').replace(aID,bID);
new MooDialog.Confirm('Soll der Termin gelöscht werden?', function(){
del.send({data : "id=" + deleteID});
}, function(){
new MooDialog.Alert('Schon Konfuzius hat gesagt: Erst denken dann handeln!');
});
});
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
var safe = new Request.HTML(
{
url: 'termin_safe.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
}
});
$$('input.edit').addEvent( 'click', function(e){
e.stop();
var aID = 'edit_', bID = '';
var editID = this.getProperty('id').replace(aID,bID);
edit.send({data : "id=" + editID});
$('edit_hide').slide('toggle');
});
});
</script>
Here the PHP Part that makes the Edit Form:
<?php
$cKey = mysql_real_escape_string($_POST['id']);
$request = mysql_query("SELECT * FROM fusspflege WHERE ID = '".$cKey."'");
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
}
echo '<form id="termin_edit" method="post" action="">';
echo '<div><label>Name:</label><input type="text" id="nns" name="name" value="'.$name.'"></div>';
echo '<div><label>Vorname:</label><input type="text" id="nvs" name="vorname" value="'.$vor.'"></div>';
echo '<div><label>Ort:</label><input type="text" id="nos" name="ort" value="'.$ort.'"></div>';
echo '<div><label>Telefon:</label><input type="text" id="nts" name="telefon" value="'.$tel.'"></div>';
echo '<div><label>eMail:</label><input type="text" id="nms" name="email" value="'.$mail.'"></div>';
echo '<input name="id" type="hidden" id="ids" value="'.$id.'"/>';
echo '<input type="button" id="sst" value="Speichern">';
echo '</form>';
?>
And last the Code of the termin_safe.php
$id = mysql_real_escape_string($_POST['id']);
$na = mysql_real_escape_string($_POST['name']);
$vn = mysql_real_escape_string($_POST['vorname']);
$ort = mysql_real_escape_string($_POST['ort']);
$tel = mysql_real_escape_string($_POST['telefon']);
$em = mysql_real_escape_string($_POST['email']);
$score = mysql_query("UPDATE fuspflege SET name = '".$na."', vorname = '".$vn."', ort = '".$ort."', telefon = '".$tel."', email = '".$em."' WHERE ID = '".$id."'");
As far as i can see the request does work but the data is not updated! i guess somethings wrong with the things posted
For any suggestions i will be gladly happy!
PS after some comments: I see the problem in this part:
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
The "Edit" request opens the form with the prefilled input fields and then attaches a click event to the submit button which should call a new request when clicked.
This third request i fail to pass the data of the input fields. i tried to get the value of each field like this:
var name = $('nns').getProperty('value');
and pass it this way
.send({data : "name=" + name});
did not work so far
PPS:
as requested the code that makes the html from main site
<?php $request = mysql_query("SELECT * FROM fusspflege");
echo '<form id="fusspflege" method="post" action="">';
echo '<table class="fuss_admin">';
echo '<tr><th>Name</th><th>Vorname</th><th>Ort</th><th>Telefon</th><th>eMail</th><th>Uhrzeit</th><th>Datum</th><th></th><th></th></tr>';
echo '<tr><td colspan=8 id="upd"></td></tr>';
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
$dat = $row->datum;
$uhr = $row->uhrzeit;
echo '<tr><td>'.$name.'</td><td>'.$vor.'</td><td>'.$ort.'</td><td>'.$tel.'</td><td>'.$mail.'</td><td>'.$uhr.'</td><td>'.$dat.'</td>';
echo '<td><input id="delete_'.$id.'" class="delete" type="button" value="X"></td>';
echo '<td><input id="edit_'.$id.'" class="edit" type="button" value="?"></td>';
echo '</tr>';
}
echo '</table>';
echo '</form>';
echo '<div id="edit_hide"></div>';
?>
UPDATE:
<form action="" method="post" id="termin_edit">
<div>
<label>
Name:
</label>
<input type="text" value="NAME" name="name" id="nns">
</div>
<div>
<label>
Vorname:
</label>
<input type="text" value="Marianne" name="vorname" id="nvs">
</div>
<div>
<label>
Ort:
</label>
<input type="text" value="MArkt Wald" name="ort" id="nos">
</div>
<div>
<label>
Telefon:
</label>
<input type="text" value="" name="telefon" id="nts">
</div>
<div>
<label>
eMail:
</label>
<input type="text" value="info#rudolfapotheke.de" name="email" id="nms">
</div>
<input type="hidden" value="115" id="ids" name="id">
<input type="button" value="Speichern" id="sst">
</form>
Update:
This is the mootools script based on the form you gave me that should work with your html:
$('sst').addEvent('click', function(event) {
var data;
event.stop();
var myInputEl = $$('#termin_edit input');
for(var i=0; i<myInputEl.length; i++){
if(i == 0)
data = myInputEl[i].name + "=" + myInputEl[i].value;
else
data += "&" + myInputEl[i].name + "=" + myInputEl[i].value;
}
myRequest.send(data);
});
Also add alert to your Request call back for the edit just to test if the ajax worked:
onSuccess: function(responseText) {
alert("done! " + responseText);
},
onFailure: function() {
alert("failed");
}
On the php side create a new PHP file and put the following in it and have ajax target it:
<?php
print_r($_POST);
?>
The Ajax should return the $_POST array in the alert box.

Categories