Using JSON to select a Dropbox option - php

I am using Json to retrieve elements from mysql and insert them into form boxes. Displaying in form boxes(text type) was not a problem but in my html one of my form structure is dropbox ... How should i display info that is in the database to the one that is in dropbox??
Here is the code that i used for displaying elements in form type (text). One of them is dropbox in the html.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='rno']").val(json.rno);
$("input[name='url']").val(json.url);
}, "json");
});
</script>
</head>
<body>
<form id="myForm" method="post">
id: <input type="text" name="id"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
<p>title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
Institution: <select name="institution">
<option value="abc">abc</option>
<option value="cdf">cdf</option>
</select>
</form>
<div id="age"></div>
</body>
</html>
PHP part or script_1.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to DB part
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
**//i am not using $row['institution'] (no institution or dropbox part)**
$abc_output = array('title' => $row['title'],'rno' => $row['reportno'],'url' => $row['calc_url']);
}
}
echo json_encode($abc_output);
}
}
?>
Help appreciated.John.

var option1 = new Option("InstitutionName1","InsitutionValue1");
var option2 = new Option("InstitutionName2","InsitutionValue2");
document.myForm.institution.options.length = 0;
document.myForm.institution.options[0] = option0;
document.myForm.institution.options[1] = option1;
This is the way its done normally. In this particular case, you may want to have a for loop or something or jQuery's each(..).

#John
You can put the following snnipet of code at the end of the script tag:
for (item in json.institution) {
$('select[name="institution"]').html('').append('<option value="' + json.institution[item].value + '">' + json.institution[item].text + '</option>');
}
where:
json.institution is a named array that will be returned along with the other form fields by your .php script.
json.institution[item].value is the value of each option.
json.institution[item].text is the text of each option.
The .html('') code is for clear the previous loaded select options.

Related

Adding/Removing form fields with Php

I have a form which gives the ability for the user to add additional fields form to the form and it selects data from the database for the select/options.
It works ok but not entirely correct and am wondering if somebody wouldn't mind casting an eye on the code to see if can be done in a much cleaner way.
The main issue being that the select isn't sending the correct value across to the action script.
HTML output of the form:
<?php $dashboardId = $_GET['dashboard_id']; ?>
<form action="cm.php" method="POST">
<input type="hidden" name="dashboardId" value="<?php echo $dashboardId; ?>">
<div id="exercises">
<div class="team">
<select name="teamId[]">
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="remove">x</button>
</div>
</div>
<button id="add_exercise">add more</button>
<br>
<input type="text" name="memberName">
<br>
<input type="submit" name="submit" value="Create Member" />
</form>
So the above renders out my simple form. The second part the JQuery that handles the facility to add additional select fields.
<script type="text/javascript">
$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="team"><select name="teamName[]"><?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?> </select><button class="remove">x</button></div>');
return false; //prevent form submission
});
$('#exercises').on('click', '.remove', function() {
$(this).parent().remove();
return false; //prevent form submission
});
</script>
Now as can be seen it isn't the neatest of solutions combining the jQuery with the Php however I am not sure how else I would separate it out? So what is happening is when I do a var_dump($_POST) I see that the generated select passes ["teamName"]=> array(1) { [0]=> string(3) "211" where it should be passing ["teamId"]=> array(1) { [0]=> string(3) "211"
I am fully aware it is open to SQL injection but for now I am just trying to make this little part work.
update - team table scehema
Main.php File
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="wrapper">
<div>
<select class="options" name="">
<option value="1">item_1</option>
<option value="1">item_2</option>
<option value="1">item_3</option>
</select>
</div>
</div>
<button type="button" class="addme" name="button">Add More</button>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$('.addme').click(function(){
$.ajax({
url:'getData.php',
type:'GET',
success:function(result){
console.log(result);
$('.wrapper').append(result);
}
})
});
});
getData.php File
<select>
<option value='1'>Item1</option>
<option value='2'>Item2</option>
<option value='3'>Item3</option>
</select><br>
In this example getData file data was static but you have write query to get dropdown list data and pass in success response.

How to save the value of the checked checkbox to the database

I have here checkboxes that have a different prices and each have a different titles. When the user clicks the checkbox, it will view the price in the total field. When the user now clicks the save button, I want now to save the total to the database and save the titles of the checked checkbox to categories. The titles that will be save to the one row of the database must be separated by comma (,).
This is my HTML codes:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<link rel="stylesheet" type="text/css" media="screen" href="css/master.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="js/jquery.min.js"></script>-->
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<form action="" method="post">
<input type="checkbox" name="checkbox1" value="₱20"> Red </br>
<input type="checkbox" name="checkbox1" value="₱30"> Blue </br>
<input type="checkbox" name="checkbox1" value="₱40"> Green </br>
</br></br>
Total: <input type="text" name="total" readonly>
<input type="submit" name="save" value="SAVE">
</form>
<script type="text/javascript">
$(function(){
//bind the change event to the checkboxes
$('input[name="checkbox1"]').change(function(){
var total = 0;
//get value from each selected ckeck box
$('input[name="checkbox1"]:checked').each(function(){
var tval = $(this).val();
//remove ₱ sign from value
//convert it to a flot
//plus it to the total
total += parseFloat(tval.replace("₱",""));
});
//finally display the total with a ₱ sign
$('input[name="total"]').val("₱ " + total);
});
});
</script>
</body>
</html>
I don't have any idea in how to save the titles of the checkboxes to one row (CATEGORY) of the database. The total price must be save too in the TOTAL field in the database.
Table name: PRODUCTS
Columns: CATEGORY, TOTAL
Example data saved in the database:
CATEGORY:[Red, Blue]
TOTAL: [50]
If you need to colors, you need to get the next sibling from the binded checkbox, then you could create another hidden form for colors since you set the checkbox values as prices. Rough example:
<form action="" method="post">
<input type="checkbox" name="checkbox1" value="20"> Red </br>
<input type="checkbox" name="checkbox1" value="30"> Blue </br>
<input type="checkbox" name="checkbox1" value="40"> Green </br>
</br></br>
<!-- hidden input colors -->
<input type="hidden" name="colors" value="" />
Total: <input type="text" name="total" readonly>
<input type="submit" name="save" value="SAVE">
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var colors = [];
//bind the change event to the checkboxes
$('input[name="checkbox1"]').change(function(){
var total = 0;
//get value from each selected ckeck box
$('input[name="checkbox1"]:checked').each(function(){
var tval = $(this).val();
total += parseFloat(tval);
});
//finally display the total with a ₱ sign
$('input[name="total"]').val("₱ " + total);
// handle colors
var color = $.trim($(this)[0].nextSibling.nodeValue); // get the name
var i = colors.indexOf(color);
if(i != -1) {
colors.splice(i, 1); // remove if unchecked
} else {
colors.push(color); // push if checked
}
var temp = colors.join(', ');
$('input[name="colors"]').val(temp);
});
});
</script>
The PHP:
<?php
$db = new mysqli('localhost', 'username', 'password', 'database');
$stmt = $db->prepare('INSERT INTO `PRODUCTS` (`CATEGORY`, `TOTAL`) VALUES (?, ?)');
if(isset($_POST['save'])) {
$total = (int) str_replace('₱ ', '', $_POST['total']); // remove peso sign
$colors = $_POST['colors'];
$stmt->bind_param('si', $colors, $total);
$stmt->execute();
}
?>
Give them different names
<input type="checkbox" name="Red" value="₱20"> Red </br>
<input type="checkbox" name="Blue" value="₱30"> Blue </br>
<input type="checkbox" name="Green" value="₱40"> Green </br>
and change your jquery a little bit:
//bind the change event to the checkboxes
$('input[name="checkbox"]').change(function(){..}
then access the attribute name:
var name = $(this).attr("name");
DEMO
$(function(){
var total = 0;
var colors = "";
$("input[type=checkbox]").change(function(e) {
var selected_color = $('input[type=checkbox]:checked');
colors = selected_color.map(function() {
return $(this).attr("name");
}).get().join(', ');
//alert(colors);
selected_color.each(function(){
var tval = $(this).val();
total += parseFloat(tval.replace("₱",""));
});
//alert(total);
});
$( "form" ).submit(function( event ) {
$.ajax({
type: "POST",
url: "your_script.php",
data: { category:colors, total: total},
success: function(data) {
alert('success');
}
});
});
});
PHP
echo $_POST['categor'];
echo $_POST['total'];
As for the insert provide this is straight for forward, you did not specify which driver you use, but you can consult #Ghost answer for mysqli
DEMO
well this seems to be a problem to the super extraordinary label element!!! (i'm so stupid, i can't beat my impetus -.-)
you can put it in a label like this:
Red
so each label identify each checkbox
so you can (if it is PHP):
$labels = $_POST['labels'];
and supposing that you have a normalized DB like this(everything else is only play with strings):
| ID | CATEGORY |
for($i=0; $i < count($labels); $i++){
mysqli_query($con,"Insert into CATEGORY(categoryname) values(' "+$labels[$i]" '); ");
}
PD: this code wasn't tested.
You need to write some server side code that will take the form data and write it to the database - this would be usually written in PHP or ASP with the bit writeing data to the database in SQL.

Pass data from dynamic select box with ajax to php without submit or reload

I want to create two select boxes: One that gets it's options from a database and the other that gets it's options depending on the value of the first select box.
My current code is below (I got the value from the first box with an alert, but don't know how to get it in the sql query for the second box). My document name is tutorial.php and I'm not using any other files except for the database functions, which are in include/config.php.
I've followed dozens of tutorials and stack overflow answers, but I can't get it to work. How can I get the select values to the php code on the same page?
jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="js/script.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "#shoot" ).change(function(){
id_firstSelect = $("#shoot").val();
loadSecondSelect(id_firstSelect);
});
function loadSecondSelect(first_id)
{
$("#model").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#model").empty();
$("#model").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#model").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}
});
</script>
form with php functions:
<form action="" method="POST" enctype="multipart/form-data">
<div>
<select name="category">
<option value="paard" selected>Paarden</option>
<option value="hond">Honden</option>
<option value="mens">Mensen</option>
<option value="eigen">Eigen werk</option>
</select>
<input type="file" name="files[]" multiple id="file"/><p>
Ophalen uit database shoots:
<select name="shoot" id="shoot">
<?php
$values = mysql_query("SELECT distinct name FROM shoots") or die(mysql_error());
//$numrows = mysql_num_rows($values);
while ($result=mysql_fetch_array($values)){
echo "<option value='".$result['name']."'>".$result['name']."</option>";
}
?>
</select><p>
<select name="model" id="model"></select>
<label class="radio">Portfoliomateriaal</label>
<input type="radio" name="folio" value="TRUE" /> <span>Ja</span>
<input type="radio" name="folio" value="FALSE" checked /> <span>Nee</span><p>
<input type="submit" value="Upload" id="submit" />
</div>
</form>
In the first select, you could call a function with the id of the select to filtrate the data of the second select like:
in the first select you could do this to fill the second with the first id:
$( "#id_firstSelect" ).change(function()
{
id_firstSelect = $("#id_firstSelect").val();
loadSecondSelect(id_firstSelect);
}
and call the function to load the second select
function loadSecondSelect(first_id)
{
$("#id_secondSelect").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#id_secondSelect").empty();
$("#id_secondSelect").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#id_secondSelect").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

Submit form in div with ajax, return php in div without refresh

I have an index page with three buttons at the top. On the click of each button a php file is loaded into the main div. One of these buttons loads a form that users fill out and submit. On submitting of the form I need it to not refresh the page and to load the resulting data into a div on the form page...not the main div.
If I load the form page on it's own (ie, not by clicking on the button, but just typing in the address of the form itself)...everything works fine. The form validation works, it submits without a refresh and the resulting data is returned into the results div on the form.
However, I load the index page and click on the button to load the form. The form loads correctly, but when I click submit it just refreshes the page...which causes the form to disappear since the div into which it is loaded is originally hidden. Also, the form doesn't validate and doesn't execute the php action.
Again, the form and its associate php work perfectly on their own. The issue only comes up when I load the form in the index page. So I'm assuming that this issue has something to do with me loading it into a div on the index page. Any help would be greatly appreciated.
Index code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="header">
<center><h2>OMS Tutoring Database</h2></center>
</div>
<div id="navbar">
<center>
<button class="navbutton" id="buttonview" type="button">View Tutoring Lists</button>
<button class="navbutton" id="buttonadd" type="button">Add Students</button>
<button class="navbutton" id="buttonadmin" type="button">Admin</button>
</center>
<br>
</div>
<div id="content"></div>
<script>
$(document).ready(function() {
$('#buttonview').click(function(){
$('#content').load('tutoring.php', function(){
});
});
$('#buttonadd').click(function(){
$('#content').load('addtest.php', function(){
});
});
$('#buttonadmin').click(function(){
$('#content').load('admin.php', function(){
});
});
});
</script>
</body>
</html>
Form Code
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addstudent").validate({
debug: false,
rules: {
studentid: "required",
teacher: "required",
assignment: "required",
date: "required",
},
messages: {
studentid: "Please enter the student's ID number.",
teacher: "Please enter your name.",
assignment: "Please select a tutoring assignment.",
date: "Please select a day.",
},
submitHandler: function(form) {
$.ajax({
url: 'add.php',
type: 'POST',
data: $("#addstudent").serialize(),
success: function(data) {
$("#studentid").val("");
$('#studentid').focus();
$("#results").empty();
$("#results").append(data);
}
});
return false;
}
});
});
</script>
</head>
<title>OMS Tutoring - Add Student</title>
<body>
Use this form to add students to the tutoring list.
<p>
<div style="float:left;width:100%;margin-bottom:10;">
<div>
<form name="addstudent" id="addstudent" action="" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>
<div><label for="day">Date</label><select name="date" id="date">
<option value="">Please select a day</option>
<option value="mon">Monday <? echo $monday; ?></option>
<option value="tue">Tuesday <? echo $tuesday; ?></option>
<option value="wed">Wednesday <? echo $wednesday; ?></option>
<option value="thu">Thursday <? echo $thursday; ?></option>
<option value="fri">Friday <? echo $friday; ?></option>
</select></div>
<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>
<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>
<input type="submit" name="submit" value="submit">
</fieldset>
</form></div></div>
<div id="results" style="margin-left:4;width:350;"><div>
</body>
</html>
Form processing php code:
<?php
$mysqli = new mysqli('localhost', 'xxx', 'xxx', 'xxx');
$studentid = $_REQUEST['studentid'];
$day = $_REQUEST['date'];
$assignment = $_REQUEST['assignment'];
$teacher = $_REQUEST['teacher'];
$dayquery = $mysqli->query("SELECT date FROM days WHERE day='$day'");
$dayresult = $dayquery->fetch_array();
$date = array_shift($dayresult);
$timestamp = date('Y-m-d H:i:s');
$mysqli->query("INSERT INTO assign (id, assignment, assignteacher, date, timestamp)
VALUES ('$studentid', '$assignment', '$teacher', '$date', '$timestamp')");
$namequery = $mysqli->query("SELECT first, last FROM students WHERE students.id='$studentid'");
$nameresult = $namequery->fetch_array();
echo $nameresult['first'].' '.$nameresult['last'].' successfully added.';
$teacherquery = $mysqli->query("SELECT assignteacher FROM assign WHERE id='$studentid' AND date='$date'");
$rowcount = $teacherquery->num_rows;
if ($rowcount > 1) {
while ($row = $teacherquery->fetch_array()) {
$teachernames[] = $row[0];
}
$teachers = implode(', ', $teachernames);
echo '<br><br>Caution: '.$nameresult['first'].' '.$nameresult['last'].' has already been added by the following teachers: '.$teachers.'. ';
echo 'They may have precedence.';
}
else {
}
$alreadyadded = $mysqli->query("SELECT assign.id, students.first, students.last, assign.assignment, assign.assignteacher FROM assign
LEFT JOIN students
ON assign.id=students.id
WHERE assign.date='$date' AND assign.assignteacher='$teacher'
ORDER BY assign.assignment ASC, students.last ASC");
echo '<br><br><br>You already have the following student(s) assigned to tutorials on this day';
echo '<table border="1">';
while ($row = $alreadyadded->fetch_array()) {
echo '<tr><td>'.$row['id'].'</td><td>'.$row['first'].'</td><td>'.$row['last'].'</td><td>'.$row['assignment'].'</td></tr>';
}
?>
When you load the form into your page using the load method, most browsers delete the <head> tag.
As from the jquery website:
During this process, browsers often filter elements from the document
such as <html>, <title>, or <head> elements. As a result, the elements
retrieved by .load() may not be exactly the same as if the document
were retrieved directly by the browser.
So, include your javascript in the main page instead of in the form page, or manually add the javascript to your main page dynamically.

Categories