PHP + Javascript dynamic div for dynamically adding inputs in form - php

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>

Related

Retrieving data from database that matches user input using AJAX

The given below is my php code, I want to extract values from database that matches the text inserted by user in text field when clicked on submit button using AJAX.
The given below is the code:
<!doctype html>
<html>
<head>
<title>Bootstrap Table</title>
<link rel="stylesheet" href="bootstrap/bootstrap-4.0.0-alpha.6-dist/css/bootstrap.min.css">
<script src="bootstrap/jquery-3.1.1.min.js"></script>
<script src="bootstrap/bootstrap-4.0.0-alpha.6-dist/js/bootstrap.min.js"></script>
<style>
.container{margin:auto;}
</style>
</head>
<body>
<div class="container">
</div>
<div class='col-sm-3' style='margin-left:10%;'>
<form class='navbar-form' action='' method='POST'>
<div class='input-group'>
<input type='text' class='form-control' placeholder='Search' name='srch-term' id='search_data'>
<div class='input-group-btn'>
<input class='btn btn-search' type='submit' id='search_button' style='cursor:pointer;'>Search</button>
</div>
</div>
</form>
</div>
<div class="result">
</div>
<script id="source" language="javascript" type="text/javascript">
$('#search_button').click(function() {
var search_data = 'input[name=srch-term]'.val();
$.ajax({
type: "POST",
url: 'bootstrap_table_db2.php',
data: {search: search_data},
success: function(result) {
for (var i in result) {
var row = result[i];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
result+= "<tr>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>";
}
$(".result").html(result);
}
});
});
</script>
</body>
</html>
The given below is bootstrap_table_db2.php.
<?php
mysql_connect("localhost", "root", "password") || die(mysql_error());
mysql_select_db("emp") || die(mysql_error());
if(isset($_POST['search']) && !empty($_POST['search'])) {
$result2 = mysql_query("SELECT * FROM employee WHERE Employee_name = 'search'");
$data2 = array();
while ( $row = mysql_fetch_row($result2) ) {
$data2[] = $row;
}
echo json_encode( $data2 );
}
?>

php form that requests data based on user select

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);
?>
}

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

Is there a limit on the amount of JavaScript Files on your head?

I'm asking because every time I use a second javascript my code gets buggy. At first the JS file was one and I was trying to make it work for both the select tags I'm working with. I wasn't able to implement it. Called it quiets and copied it but renamed everything to avoid any conflicts in the name. But my errors keep on happening. Maybe there's something wrong with my code or?
html Head
<head>
<title>Packages</title>
<link rel="icon" type="image/ico" href="../favicon.ico"/>
<link rel="stylesheet" type="text/css" href="../style/style_p.css"/>
<script type="text/javascript" src="../style/add_fields.js"></script>
<script type="text/javascript" src="../style/addMoreFields.js"></script>
<h1><img src="../images/Logo.png" alt="Logo"></h1>
</head>
JS 1
var instance = 0;
function moreFields(parentHome, cloneHome) {
// Check if there isn't more than 3 fields
if(instance != 3) {
instance++;
// Create a child
var TempClone = document.getElementById(parentHome).cloneNode(true);
// remove templet clone's id to avoid future confusion
TempClone.id = "";
TempClone.style.display = 'block';
/* Get the cloned templet's
* Children. Here we will make
* only the ones who have a name
* unique.
*/
var cloneC = TempClone.childNodes;
for(var i = 0; i < cloneC.length; i++) {
var ChildName = cloneC[i].name;
if(ChildName)
cloneC[i].name = ChildName + instance;
}
// Locate clone's home
var insertHere = document.getElementById(cloneHome);
// Place clone in home
insertHere.parentNode.insertBefore(TempClone,insertHere);
}
}
window.onload = function() {
moreFields('SnackBox', 'SnackPlate');
}
JS2
var counter = 0;
function addMoreFields(srcHome, cloneHome) {
// Check if there isn't more than 3 fields
if(counter != 3) {
counter++;
// Create a child
var template = document.getElementById(srcHome).cloneNode(true);
// remove templet clone's id to avoid future confusion
template.id = "";
template.style.display = 'block';
/* Get the cloned templet's
* Children. Here we will make
* only the ones who have a name
* unique.
*/
var copy = template.childNodes;
for(var i = 0; i < copy.length; i++) {
var cloneName = copy[i].name;
if(cloneName)
copy[i].name = cloneName + counter;
}
// Locate clone's home
var endLocation = document.getElementById(copyHome);
// Place clone in home
endLocation.parentNode.insertBefore(Template,endLocation);
}
}
window.onload = function() {
addMreFields('SoupBox', 'SoupBowl');
}
html code
<td><div id="SnackBox" style="display:none">
<select id="dfood" name="dfood">
<option>--Select--</option>
<?php
$result = mysql_query("SELECT * FROM survival_mode.dryfood_t", $link);
while($row = mysql_fetch_array($result)) {
echo "\n\t\t\t\t\t\t<option value='{$row['dfood_ID']}'>{$row['dfood_name']}</option>";
}
echo "\n";
?>
</select>
<input name="df_qty" type="text" placeholder="qty" size="1" maxlength="1"/>
<?php
if($climate == "warm") {
echo "\n\t\t\t\t<input type='button' value='-' onclick='if(instance > 1){instance--; this.parentNode.parentNode.removeChild(this.parentNode);}' />";
echo "\n\t\t\t\t<input type='button' value='+' onclick='moreFields(\"SnackBox\", \"SnackPlate\");' />";
}
echo "\n";
?>
</div>
<span id="SnackPlate"></span>
</td>
<td><div id="SoupBox">
<select id="Soup" name="Soup">
<option>--Select--</option>
<?php
$result = mysql_query("SELECT * FROM survival_mode.soup_t", $link);
while($row = mysql_fetch_array($result)) {
echo "\n\t\t\t\t\t\t<option value='{$row['soup_ID']}'>{$row['soup_name']}</option>";
}
echo "\n";
?>
</select>
<input name="s_qty" type="text" placeholder="qty" size="1" maxlength="1" />
<?php
if($climate == "cold") {
echo "\n\t\t\t\t<input type='button' value='-' onclick='if(counter > 1){counter--; this.parentNode.parentNode.removeChild(this.parentNode);}' />";
echo "\n\t\t\t\t<input type='button' value='+' onclick='addMoreFields(\"SoupBox\", \"SoupBowl\");' />";
}
echo "\n";
?>
</div>
<span id="SoupBowl"></span>
</td>

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.", ";}

Categories