I write this little script of PHP but when I press the button "Add" it don't add the value to the json.json file, can you tell me what is wrong? The objective is take the values introduced by user on the box add.name and add-link and save it to the json.json file. Have I to call the php script on a html line?
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
<?php
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($json, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $jsonString);
?>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" name="addname" id="add-name" placeholder="Name"></input>
<input type="text" name="addlink" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Box/Table Configuration (Sites/edit/delete)
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
var el1 = document.getElementById('edit-name1');
el.value = Checker[item].name;
el1.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
var url1 = el1.value;
if (url) {
Checker[item].url = url1.trim();
Checker[item].name = url.trim();
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
//Close button (Edit bar)
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
I think you are not using your variables in the right way. json_decode should use $jsonContents and file_put_contents should use $json
Since you are using post variables, you might want to check if it is a post first.
Try it like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($jsonContents, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $json);
}
Related
I'm trying to post new data into my json file by using jquery by entering the values of the input but nothing happens when I do. I apologize in advance for this slightly dumb question and I'm very grateful for any help!
I'm very new to programming but I have no clue if this is even possible to do. Below is my 'index.php' file where my jquery and button is to add new data.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="name">
<input type="text" id="grade">
<button id="btn">Add</button>
</body>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/mytest/json.php', function(data) {
for (i=0; i < data.length; i++) {
if (data[i].grade < 5) {
document.write("<p style='color: red;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
} else {
document.write("<p style='color: green;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
}
}
});
// posting the orders
$('#button').on('click', function() {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'http://localhost/mytest/json.php',
data: order,
success: function(newStudent) {
}
})
});
});
</script>
</html>
Here below is the JSON file I created with PHP (json.php):
<?php
$student1 = array(
"name"=>"ali",
"grade"=>"7"
);
$student2 = array(
"name"=>"John",
"grade"=>"4"
);
$student3 = array(
"name"=>"Martha",
"grade"=>"2"
);
$student4 = array(
"name"=>"Jullie",
"grade"=>"8"
);
$student5 = array(
"name"=>"Morgan",
"grade"=>"4"
);
$students = array($student1, $student2, $student3, $student4, $student5);
$j = json_encode($students); // we 'encode' the array into a JSON format
echo $j;
?>
Hello this is a fixed version of your code
Persisten data
Remove dumplicate code for pass grade
Create a div with students data(json content)
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
Name: <input type="text" id="name"><br>
Grade: <input type="text" id="grade"><br>
<button id="button">Add</button>
<div id="students">
</div>
</body>
<script>
$(document).ready(function () {
// fill students div content with document ready
updateStudents();
$('#button').on('click', function () {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'json.php',
data: order,
success: function (newStudent) {
console.log("Success");
$("#students").append(setStudents($('#name').val(), $('#grade').val()));
}
})
});
function updateStudents() {
$.getJSON('students.json', function (data) {
for (i = 0; i < data.length; i++) {
$("#students").append(setStudents(data[i].name, data[i].grade));
}
});
}
function setStudents(name, grade) {
var color = 'green';
if (grade < 5) {
color = 'red';
}
return "<p style='color: " + color + ";'>Name: " + name + "<br>Grade: " + grade + "</p>"
}
});
</script>
</html>
json.php
<?php
$file = "students.json";
$content = file_get_contents($file);
if ($content == null) {
$data[] = $_POST;
$jsonData = json_encode($data);
file_put_contents($file, $jsonData);
} else {
$data = $_POST;
$tempArray = (array) json_decode($content);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents($file, $jsonData);
}
echo $jsonData;
students.json
Note: the file could be empty this is just some data
[{"name":"Pedro","grade":"10"},{"name":"Juan","grade":"10"},{"name":"Lopez","grade":"10"},{"name":"Maria","grade":"5"},{"name":"Miguel","grade":"5"},{"name":"Juana","grade":"4"},{"name":"hugo","grade":"8"},{"name":"Nano","grade":"2"}]
If nothing is happening, it may be that you need to change
$('#button')
to
$('#btn')
And, no dumb questions! We're all in this together. Best of luck to you.
I am trying mas a simple HTTP post request using AXIOS.Its like an Ajax request to retrieve the data . Here is the HTML. Its sends a post request to the getData.php.
<!doctype html>
<html>
<head>
<title>axios - post example</title>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
</head>
<body class="container">
<h1>Axios.post</h1>
<form role="form" class="form" onsubmit="return false;">
<div class="form-group">
<label for="data">Output</label>
<textarea id="data" class="form-control container" rows="5"></textarea>
</div>
<button id="post" type="button" class="btn btn-primary">POST</button>
</form>
<!--<div id="output" class=""></div>-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
(function () {
document.getElementById('post').onclick = function () {
var output = document.getElementById('data');
axios.post('getData.php')
.then(function (res) {
// console.log(res.data);
output.className = 'container';
for (i = 0; i < res.data.length; i++) {
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
}
})
.catch(function (err) {
output.className = 'container text-danger';
output.innerHTML = err.message;
});
};
})();
</script>
</body>
</html>`
In the getData.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password,"db_test");
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$resultArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
return;
} else {
echo "0 results";
}
$conn->close();
?>
But when i am trying to for loop through the array it returns only the last row.It fetches the data from the table and create an array. Whats wrong with the for loop ?
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
will just replace everything previously added.
output.innerHTML += res.data[i].id + "\n" + res.data[i].name;
would fix your problem.
Because your overwriting output.innerHTML In for loop so last value only exists .
use appendChild()
output.appendChild(res.data[i].id + "\n" + res.data[i].name);
Im trying to get random questions from my sql table.The rand() function is not working. The rand() function for 'answers' is working but not for 'questions' row. Where am I going wrong? . Can anyone give a solution to this?
index.php
<?php
$msg = "";
if(isset($_GET['msg'])){
$msg = $_GET['msg'];
$msg = strip_tags($msg);
$msg = addslashes($msg);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quiz Tut</title>
<script>
function startQuiz(url){
window.location = url;
}
</script>
</head>
<body>
<?php echo $msg; ?>
<h3>Click below when you are ready to start the quiz</h3>
<button onClick="startQuiz('quiz.php?question=1')">Click Here To Begin</button>
</body>
</html>
questions.php
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysql_query("SELECT id FROM questions");
$numQuestions = mysql_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="text" name="email">
<input type="submit" value="Finish">
</form>';
exit();
}
$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' order by RAND() LIMIT 1");
while($row = mysql_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="checkbox" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
quiz.php
<?php
session_start();
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1;
if(!isset($_SESSION['qid_array']) && $question != 1){
$msg = "Sorry! No cheating.";
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['qid_array']) && in_array($question, $_SESSION['qid_array'])){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Quiz Page</title>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "checkbox=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&checkbox="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Thanks, Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
</script>
</head>
<body onLoad="getQuestion()">
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<h1>PONG</h1>
</div>
<script type="text/javascript">countDown(20,"counter_status");</script>
</body>
</html>
SELECT * FROM questions WHERE id='$question'
Seems that you're selecting exactly one question at a time, so there's nothing to sort randomly.
If you want to select a random question, query probably should look like this:
SELECT * FROM questions WHERE 1=1 order by RAND() LIMIT 1
... but that would require rewriting some of related code: for example, you won't need mandatory question get parameter every time.
This is my simple form which contains employe name, empno, empsal and doj(date of joining). Here i'm posting the values of this form through XMLHttpRequest object through send asynchronously and updating the requestTxt in the DOM in myDiv.
Here when i pass the parameters some thing like this, i can able to get the values in php echo $empname. "is my name";
var params = "empname="+myname+"&empno="+myno+"&empsal="+mysal+"&empdoj="+mydoj;
But at the same time, if i pass it as a object, stringified i don't know why it is not printing
var params = {
"empname":myname,
"empno":myno,
"empsal":mysal,
"empdoj":mydoj
};
var jsonText = JSON.stringify(params);
alert(jsonText);
Here is my code
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="windows-1252">
<title>Sample form</title>
<style>
table td{
border-collapse:collapse;
border:1ps solid #000;
}
.hide{
display:none;
}
</style>
<script type="text/javascript" src="util.js"></script>
</head>
<body>
<form name="sampleForm" id="sampleForm" action="javascript:return false;">
<table width="40%">
<tr>
<td>Employee Name:</td>
<td><input type="text" name="empname" id="empname"/></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="empno" id="empno"/></td>
</tr>
<tr>
<td>Employee salary:</td>
<td><input type="text" name="empsal" id="empsal"/></td>
</tr>
<tr>
<td>Employee DOJ:</td>
<td><input type="text" name="empdoj" id="empdoj"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submitBtn" id="submitBtn1" /></td>
</tr>
</table>
<div class="hide" id="myDiv"></div>
</form>
<script type="text/javascript">
var subform = document.getElementById("sampleForm");
subform.onsubmit = function(){
var myReq;
var uRLTxt = "loginCheck.php";
var myname = document.getElementById("empname").value;
var myno = document.getElementById("empno").value;
var mysal = document.getElementById("empsal").value;
var mydoj = document.getElementById("empdoj").value;
/*var params = "empname="+myname+"&empno="+myno+"&empsal="+mysal+"&empdoj="+mydoj; */
var params = {
"empname":myname,
"empno":myno,
"empsal":mysal,
"empdoj":mydoj
};
var jsonText = JSON.stringify(params);
alert(jsonText);
myReq = new XMLHttpRequest();
myReq.open("POST",uRLTxt,true);
myReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//myReq.setRequestHeader("Content-type", "application/JSON; charset=utf-8");
myReq.setRequestHeader("Content-length", jsonText.length);
//alert(jsonText.length);
myReq.setRequestHeader("Connection", "close");
myReq.onreadystatechange = function() {
if(myReq.readyState == 4 && myReq.status == 200){
var return_data = myReq.responseText;
console.log(return_data);
document.getElementById("myDiv").style.display = "block";
document.getElementById("myDiv").innerHTML = return_data;
}
}
myReq.send(jsonText);
return false;
};
</script>
</body>
</html>
Php Code - loginCheck.php
<?php
$empname = isset($_REQUEST['empname']);
$empno = isset($_REQUEST['empno']);
$empsal = isset($_REQUEST['empsal']);
$empdoj = isset($_REQUEST['empdoj']);
echo $empname."is my name";
?>
If you want to use javascript alone,
you want to specify the data you want to send in the send() method.
var params = {
"empname":myname,
"empno":myno,
"empsal":mysal,
"empdoj":mydoj
};
var jsonText = JSON.stringify(params);
myReq.send("totalJsonStr="+jsonText);
Decode your json string using json_decode() . Add this to your loginCheck.php
<?php
if(isset($_POST["totalJsonStr"])) {
$jsonVal = json_decode($_POST["totalJsonStr"]);
//If you want empname
print $jsonVal->{'empname'} . " is my name"; }
else { die("No Data Found"); }
?>
Try it,
<script language="javascript" src="jquery-1.4.4.min.js"></script>
<script>
var myname = document.getElementById("empname").value;
var myno = document.getElementById("empno").value;
var mysal = document.getElementById("empsal").value;
var mydoj = document.getElementById("empdoj").value;
var subform = document.getElementById("sampleForm");
subform.onsubmit = function(){
$.ajax({
url: 'loginCheck.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data:"empname=myname&empno=myno&empsal=mysal&empdoj=mydoj",
success: function(data){ alert(data); })
}, }); };
</script>
Your PHP looks like this:
<?php
$empname = isset($_REQUEST['empname']);
$empno = isset($_REQUEST['empno']);
$empsal = isset($_REQUEST['empsal']);
$empdoj = isset($_REQUEST['empdoj']);
echo $empname."is my name";
?>
But the function isset() only returns true or false, depending if a variable is set or not. Your script should look like:
<?php
// Repeat for all variables
// This is an equivalent to:
// if (isset($_REQUEST['empname'])) {
// $empname = $_REQUEST['empname'];
// }
// else {
// $empname = "";
// }
$empname = isset($_REQUEST['empname']) ? $_REQUEST['empname'] : "";
echo "{$empname} is my name";
?>
For your params string in Javascript, change this:
var params = {
"empname":myname,
"empno":myno,
"empsal":mysal,
"empdoj":mydoj
};
var jsonText = JSON.stringify(params);
alert(jsonText);
// Blah blah...
myReq.send(jsonText);
for this:
var params = {
"empname":myname,
"empno":myno,
"empsal":mysal,
"empdoj":mydoj
};
var out = new Array();
for (key in params) {
out.push(key + "=" + encodeURI(params[key]));
}
var postText = out.join("&");
alert(postText);
// Blah blah...
myReq.send(postText);
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.
Problem solved.
.change(function() had to be .live('click', function()