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.", ";}
Related
I would like to name the function devtest() in the form as developer so when a user selects the developer it is submitted with the form.
The function I have is this and it is working, it returns the results when you select an item from the dropdown:
function devtest()
{
$db = db();
$stmt = $db->prepare('SELECT developer FROM developers');
$result = $stmt->execute();
?>
<select name="Developer">
<?php
while ($row = $result->fetchArray()) {
$dev = $row['developer'];
echo "<option value='" . $row['developer'] ."'>" . $row['developer'] ."</option>";
}
echo "</select>";
}
on the page itself where I call function and have the form I have
<form method="POST">
Enter game name:
<input type="text" name="name">
<br>
Enter Price
<input type="text" name="price">
<br>
Enter Platform
<input type="text" name="platform">
<br>
Select Developer
<!--<input type="text" name="developer">-->
<?php
devtest();
?>
<br>
Enter quantity
<input type="text" name="quantity">
<br>
Enter shipping
<input type="text" name="shipping">
<br>
<input type="submit" value="save">
</form>
That form goes to this function
function addgame()
{
#$devtest = devtest();
$db = db();
#function to add the form data from the add game page to the database
if(!empty($_POST['name']) && !empty($_POST['price']) && !empty($_POST['platform']) && !empty($_POST['quantity'])&& !empty($_POST['shipping'])){
$name = SQLite3::escapeString($_POST['name']);
$price = SQLite3::escapeString($_POST['price']);
$platform = SQLite3::escapeString($_POST['platform']);
$developer = SQLite3::escapeString($_POST['Developer']);
#$developer = devtest();
$quantity = SQLite3::escapeString($_POST['quantity']);
$shipping = SQLite3::escapeString($_POST['shipping']);
if (strlen($name) < 2)
{
echo("name be 2 char or longer");
}
if (!is_numeric($price))
{
echo("price must be numbers only");
}
if (strlen($platform) < 2)
{
echo("Platform must be 2 char or longer");
}
if (strlen($quantity) < 1)
{
echo("quantity must be more than 1");
}
/*if (strlen($shipping) < 9)
{
echo("shipping must be more than $9");
}*/
else
{
$stmt = $db->prepare("INSERT INTO game (name , price , platform , Developer, quantity, shipping) VALUES ('$name' , '$price' , '$platform' , '$developer', '$quantity' , '$shipping')");
$result = $stmt->execute();
}
}
else
{
echo "Fill in all form fields";
}
}
Without using the devtest() function in the form, and using the everything works fine, I am trying to change it so those on the list can be selected but I am not sure how to pass their select through the form.
you can send data to javascript and write your function in js to add a dropdown every where you need:
...
<script>
var developer = []
</script>
.
.
.
<php>
while ($row = $result->fetchArray()) {
?>
<script>
var developer[]=<?php echo $row['developer']; ?>
</script>
<?php
}
?>
js funtion:
<script>
function devtest(elementID){
developer.forEach(index,item){
$('#'+elementID).append('<select value="'+item+'">'+item+'</select>');
}
}
</script>
}
I have edited this based on help already received. I seem to be having issues with how the information is being called from the database. I keep getting errors of no results found so to speak. I think I got a pretty good idea what might be the cause, but I am not sure to rectify this.
Originally this search function was set up differently. I had an html page that had a dropdown list each option was assigned a value, this being text i.e.
<option Value="North East">North East</option>
However because I have separate tables in the database that control the population of the drop downs, the value is no longer being text but a number.
Any ideas on how to combat this?
This is currently what I have from head to toe.
<!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=iso-8859-1" />
<title>Results</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
<style>
body {
color: #FFFFFF;
}
#theclub{
border:1px solid white;
padding: 10px;
}
label
{
font-weight:bold;
padding:10px;
}
</style>
<link rel="stylesheet" type="text/css" href="Style.css">
<script type='text/javascript' src='style2.js'></script>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<label>Country :</label> <select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select>
<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<input type="submit" value="Search" name="submit">
</form>
<?php
if(isset($_POST['submit']) && $_POST['submit'] != ""){ } //--here is the condition that is true if search button is pressed
$selectedOption = $_POST["city"];
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption)));
echo "<div id=\"Results\">";
while($row = mysqli_fetch_array($result))
{
echo "<div id=\"theclub\">";
echo "<div class=\"ClubName\">";
echo $row['EstName'];
echo "</div><br>";
echo "<div class=\"Location\">";
echo $row['EstAddress2'];
echo "</div>";
echo "<br>";
echo "<div id=\"website\"><img src=\"photos/more-info.png\" width=\"75\" height=\"25\"/> <img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div></div>";
echo "<br>";
}
echo "</div>";
mysqli_close($con);
?>
<br>
</body>
I'm shooting in the dark a bit because I'm not sure what you mean by first and second code...
If you want only one part of the code to run you need some sort of condition to check if to run it or not
If you don't want the second part of the code run right away you want to check if the post variable city is set and not empty and only run the code if the value isn't empty:
if(isset($_POST['city']) && $_POST['city'] != ""){
// your code here
}
Your second code should be enclosed within a if condition in order to run it after the first code exicution like the following way-
But first you have to add name attribute to your search button in first code-
<input type="submit" value="Search" name="submit">
and now your second code should be--
if($_POST['submit']) //--here is the condition that is true if search button is pressed
{
$selectedOption = $_POST["city"];
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption)));
echo "<div id=\"Results\">";
while($row = mysqli_fetch_array($result))
{
echo "<div id=\"theclub\">";
echo "<div class=\"ClubName\">";
echo $row['EstName'];
echo "</div><br>";
echo "<div class=\"Location\">";
echo $row['EstAddress2'];
echo "</div>";
echo "<br>";
echo "<div id=\"website\"><img src=\"photos/more-info.png\" width=\"75\" height=\"25\"/> <img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div></div>";
echo "<br>";
}
echo "</div>";
mysqli_close($con);
?>
}
I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>
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>