Function not renaming field pulled from another page - php

I have a form which is cloned when needed, inside this form I have a div, this div is replaced by a div pulled from another page which has new select options based on a select option from a above field.
Each 'cloned' forms fields are given a new name with a function, but this function seems to have trouble seeing the field that is pulled in as part of the form and isn't generating a new name for it.
Could Someone kind enough show me the way please?
function;
$(document).ready(function() {
var newNum = 2;
cloneMe = function(el) {
var newElem = el.clone().attr('id', 'container' + newNum);
newElem.html(newElem.html().replace(/form\[1\]/g, 'form['+newNum+']'));
newElem.html(newElem.html().replace(/id="(.*?)"/g, 'id="1'+newNum+'"'));
$('#cloneb').before(newElem);
$('#delete_name'+ newNum).html('<p id="rem_field"><span>Delete Line</span></p>');
newNum++;
};
$('p#rem_field').live('click', function() {
$(this).parents('div').remove();
return false;
});
});
form;
<form action='' method='post' enctype='multipart/form-data' name='form' id='form'>
<div id="container1">
<div class="instance" id="instance">
<label>Style:</label>
<select name='form[1][style]' id='style' class='style' onchange="showDim(this)">
<option value='0' class='red'>Select a style...</option>
<?php
include ('connect.php');
$getsty = $db->prepare("SELECT Style_ID, Style_Type FROM style ORDER BY Style_Type ASC LIMIT 1, 18446744073709551615;");
$getsty->execute();
while($row = $getsty->fetch(PDO::FETCH_ASSOC)) {
$Style_ID = $row['Style_ID'];
$Style_Type = $row['Style_Type'];
echo " <option value='$Style_ID'>$Style_Type</option>";
}
?>
</select>
<br />
<div class='dimdiv'>
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class='red'>Select the dimensions...</option>
</select>
</div>
<br />
<label>Colour:</label>
<select name='form[1][Colour]' id='Colour'>
<option value='0' class='red'>Select a colour...</option>
<option value='Colour1'>Colour #1</option>
<option value='Colour2'>Colour #2</option>
<option value='Colour3'>Colour #3</option>
<option value='Colour4'>Colour #4</option>
</select>
<br />
<label>Quantity:</label>
<input type='text' name='form[1][Quantity]' id='Quantity'>
<br />
</div>
<div id="delete_name" style="margin:15px 0px 0px 0px; width:120px; height:30px;"></div>
</div>
<input type="button" id="cloneb" value="Clone" onclick="cloneMe($('#container1'));" />
<input type='submit' name='submit' value='Submit' class='buttons'>
</form>
Field pulled from get_dim.php;
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class="red">Select the dimensions...</option>
<?php
$id = intval($_GET['id']);
include ('connect.php');
$getcus = $db->prepare("SELECT Dim_ID, Dim FROM dimentions WHERE Style_ID=? ORDER BY Dim ASC ");
$getcus->execute(array($id));
while($row = $getcus->fetch(PDO::FETCH_ASSOC)) {
$Dim_ID = $row['Dim_ID'];
$Dim = $row['Dim'];
echo " <option value='$Dim_ID'>$Dim</option>";
}
?>
</select>
Function to replace the dimdiv with get_dim.php;
function showDim(elem)
{
var elems = document.getElementsByClassName('style'),
groupIndex = -1,
targetDimDiv,
i;
for( i = 0; i < elems.length; ++i ) {
if( elems[i] == elem ) {
groupIndex = i;
break;
}
}
if( groupIndex == -1 )
{
return;
}
targetDimDiv = document.getElementsByClassName('dimdiv')[groupIndex];
if (elem.value == "")
{
targetDimDiv.innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function( ) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
targetDimDiv.innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","get_dim.php?id="+elem.value,true);
xmlhttp.send();
}

Your problem is, that form[1][Dim] is hard coded into get_dim.php. When you clone a form, you change the name of every element, but this AJAX request would still return a form element with name form[1][Dim] there too.
You can fix this, by reading out the current form id and passing it to get_dim.php and making the name generation there dynamic.
The parts you have to change (roughly):
replace function:
form_id = groupIndex + 1; // if I get groupIndex right
xmlhttp.open("GET","get_dim.php?id="+elem.value+"&form_id="+form_id,true);
get_dim.php:
<select name='form[<?php echo intval($_GET['form_id']); ?>][Dim]' id='Dim'>

Related

Populate datalist with mysql fields based on input from another field without reloading page

I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.
I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;}
else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
}};
xmlhttp.open("POST", "contactnames.php", true)
xmlhttp.send(str);
}
}
</script>
<?php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
echo'<option value="'.$contactnamerow['ContactName'].'">';
}
?>
Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.
Right now, it is not populating anything into the contact name field.
In index.php
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
alert('Fired');
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
// document.getElementById("contactnamesoptions").innerHTML = "working";
}
};
xmlhttp.open("POST", "response.php", true)
xmlhttp.send(str);
}
}
</script>
in response.php
<?php echo "test"; ?>
Once you've verified that works, query the database
EDIT:
Now that you've verified that, query the database in response.php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
$queryHTML = '';
$result = 0;
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
$result = 1;
$queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
}
if ($result == 1) {
echo $queryHTML;
} else {
echo 'No Builders found';
}
Note: Change the columnName in the query to your real column name

Passing 2 value from 2 dropdown into 3rd dropdown

I have tried passing value on 3rd drop down but it doenst receive any of it
it doesnt show error but it doesnt get any data from 2 dropdowns Im new to just and im trying something but it doesnt work at all pls help thank you very much
dropdown.php
<select class="form-control" style="font-size: 21px;" name="Building" id="Building" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from Building");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Building']; ?>"><?php echo $row['Building'];?></option>
<?php
}
?>
</select>
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from floor");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Floor']; ?>"><?php echo $row['Floor'];?></option>
<?php
}
?>
</select>
<div id="Dept"></div>
</div>
</div>
<script type="text/javascript ">
function change_floor(str,str1) {
if (str.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "deptajax.php?q="+str+"&d="+str1, true);
xmlhttp.send();
}
}
</script>
deptajax.php
If I use request here i shows error but if I use GET i doesnt show any error what is more usable for this scenario?
<?php
$link=mysqli_connect("localhost","id5592115_retep","Password");
mysqli_select_db($link,"id5592115_admin");
$q = $_REQUEST["q"];
$d = $_REQUEST["d"];
$res=mysqli_query($link,"select * from depttable where Flr='$d' and
Building='$q' order by deptname asc");
echo "<form method='get' action='table2.php'>";
echo '
<select class="form-control" style="font-size: 21px;" name="dept">
';
while ($row=mysqli_fetch_array($res)) {
$deptid = $row['deptid'];
$deptname = $row['deptname'];
echo "<option value='".$deptname."'>".$deptname."</option>";
}
echo "</select>";
echo '<button type="submit" class="btn btn-light
btnmove">Submit</button>';
echo "</form>";
?>
Your onclick function is call every time you select any of the dropdown , so at a time only one value is passed i.e : either str or str1 will have value . Instead to avoid this you can do like below :
When first selectbox is selected try to store it value in some variable like below :
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor"
onChange="change_floor1(this.value)">
<!--^ make another function with name change_floor1-->
<option>Select</option>
...
</select>
Then in your <script></script>do like below :
var s; // declare globally
function change_floor1(str) {
s=str; //assigning value of first-select box in "s"
}
function change_floor(str1) {
if (str1.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
//passing both value
xmlhttp.open("GET", "deptajax.php?q="+s+"&d="+str1, true);
xmlhttp.send();
}
}

PHP foreach form displaying a 3 sets of array in order

I have this form that have an "add field" function. When the add field is triggered/clicked a new set of price[],pax[] and days[] will be added it will became an array.
My question is, is there anyway or is it possible to have an outcome like this when I clicked the submit button? to display them in this order?
price[0] - pax[0] - days[0]
price[1] - pax[1] - days[1]
price[2] - pax[2] - days[2]
I tried this but it worked only for [0] and did not work on the rest [1] and [2]. PHP
foreach() {
// echo here [0]
foreach() {
// echo here [1]
foreach() {
// echo here [2]
}
}
}
Here is my code below.
<div>
<form method="post">
<div class="" id="buildyourForm">
<input name="price[]" type="number">
<select name="pax[]">
<option value="2">2</value>
<option value="3">3</value>
<option value="4">4</value>
</select>
<select name="days[]">
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="4">4 days</option>
</select>
<input type="submit" name="submit">
<div>
<input type="button" id="add_field">
</div>
</div>
</form>
</div>
Jquery/Javascript
$(document).ready(function() {
$("#add_field").click(function() {
var lastField = $("#buildyourform div:last");
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 2;
var fieldWrapper = $("<div id=\"field"+ intId + "\"/>");
fieldWrapper.data("idx", intId);
var layer_1 = $("<label ">Package "+intId+" </label>");
var layer_2 = $("<input name=\"price[]\" type=\"number\" />");
var layer_3 = $("<select name=\"pax[]\"><option value=\"2\">2</value><option value=\"3\">3</value><option value=\"4\">4</value></select>");
var layer_4 = $("<select name=\"days[]\"><option value=\"2\">2 days</option><option value=\"3\">3 days</option><option value=\"4\">4 days</option></select>");
var layer_5 = $("<input name=\"hidden[]\" type=\"hidden\" value\="+intId+"\ />");
var removeButton = $("<input type=\"button\" value=\"X\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(layer_1);
fieldWrapper.append(layer_2);
fieldWrapper.append(layer_3);
fieldWrapper.append(layer_4);
fieldWrapper.append(layer_5);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
If I am getting your question right, you want to print values like:
for($i=0; $i<count($_POST['price']); $i++){
$price = $_POST['price'][$i];
$pax = $_POST['pax'][$i];
$days = $_POST['days'][$i];
echo "$price $pax $days <br/>";
}
Try below one
$a = array(0, 1, 2);
$b = array(0, 1, 2);
$c = array(0, 1, 2);
for ($i = 0; $i < count($a); $i++) {
echo $a[$i] . $b[$i] . $c[$i];
echo '<br/>';
}
Hope it will help you.

show div in selecting option inside looping data

i have code in php:
<?php
$produk = mysql_query("SELECT * FROM produk ORDER BY id_produk DESC");
while($p=mysql_fetch_array($produk)){
<select name='urutan' onChange='yesnoCheck(this);'>
<option value='yes' selected>Yes</option>
<option value='no'>No</option>
</select>
<div id='ifY' style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
<div id='ifN' style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
}
in my jquery code:
<script>
function yesnoCheck(that) {
if (that.value == "other") {
document.getElementById("ifNon").style.display = "block";
} else {
document.getElementById("ifNon").style.display = "none";
}
if (that.value == "yes") {
document.getElementById("ifY").style.display = "block";
} else {
document.getElementById("ifY").style.display = "none";
}
if (that.value == "no") {
document.getElementById("ifN").style.display = "block";
} else {
document.getElementById("ifN").style.display = "none";
}
}
</script>
in my looping data,i try run selecting option to show div, but it just run in my first data,so cant run in another data. help me please
Try this, this should work
<?php
$produk = mysql_query("SELECT * FROM produk ORDER BY id_produk DESC");
$i = 0;
while($p=mysql_fetch_array($produk)){ ?>
<select name='urutan' onChange='yesnoCheck(this,<?= $i ?>);' rel="<?= $i ?>">
<option value='yes' selected>Yes</option>
<option value='no'>No</option>
</select>
<div id="ifY<?= $i ?>" style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
<div id="ifN<?= $i ?>" style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
<br>
<?php $i++; } ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function yesnoCheck(that,i) {
if (that.value == "yes") {
$("#ifY" + i).css("display","block")
$("#ifN" + i).css("display","none")
} else if (that.value == "no"){
$("#ifY" + i).css("display","none")
$("#ifN" + i).css("display","block")
}
}
Use Dynamic ID and name for the div and select element with using counter variable.
PHP Code
<?php
$produk = mysql_query("SELECT * FROM manufacturer ORDER BY id DESC limit 5");
$i = 1;
while($p=mysql_fetch_array($produk))
{
?>
<select name='urutan<?php echo $i?>' id="urutan<?php echo $i?>" onChange='yesnoCheck("<?php echo $i?>");'>
<option value='yes' selected>Yes</option>
<option value='no'>No</option>
</select>
<div id='ifY<?php echo $i?>' style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
<div id='ifN<?php echo $i?>' style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
<?php
$i++;
}
?>
Javascript Code
<script>
function yesnoCheck(id)
{
var that = document.getElementById("urutan"+id);
/*if (that.value == "other") {
document.getElementById("ifNon"+id).style.display = "block";
} else {
document.getElementById("ifNon"+id).style.display = "none";
}*/
if (that.value == "yes") {
document.getElementById("ifY"+id).style.display = "block";
} else {
document.getElementById("ifY"+id).style.display = "none";
}
if (that.value == "no") {
document.getElementById("ifN"+id).style.display = "block";
} else {
document.getElementById("ifN"+id).style.display = "none";
}
}
</script>
Something like this would help i guess. Also id should always be unique use class instead.
PHP code and html
<?php
$produk = mysql_query("SELECT * FROM produk ORDER BY id_produk DESC");
while($p=mysql_fetch_array($produk)){ ?>
<div> // new div added here.
<select name='urutan' onChange='yesnoCheck(this);'>
<option value='yes' selected data-selector="ifY">Yes</option> // added new data-selector attribute.
<option value='no' data-selector="ifN">No</option>
</select>
<div class='ifY commonclass' style='display: none;'> // changed id to class and added a commonclass to get all divs.
<input type=submit value=submit class=ui-btn-primary>
</div>
<div class='ifN commonclass' style='display: none;'>
<input type=submit value=submit class=ui-btn-primary>
</div>
</div>
<?php } ?>
Jquery
$('[name="urutan"]').change(function(){
var $this = $(this);
var $parentDiv = $this.parent();
var $selected = $("option:selected",$this),
$parentDiv.find('.commonclass').hide();
$parentDiv.parent().find("."+$selected.data('selector')).show();
}).trigger('change');

Dynamic drop down list not working

I am trying to pass a js var to a php var, then use that php var to go through and array and populate a drop down list. I can see that the php var is getting the right value but list2 and list3 are not being populated.
If I put the string in myself $list1 = 'somestring'; it works, but when I use $list1 = $_POST['choice']; it doesn't work.
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
<?php
echo'
<form name="menu">
<div>
<select name="list1" size="1" onchange="setOptions(document.menu.list1.options
[document.menu.list1.selectedIndex].value,document.menu.list2,document.menu.list3);">
<option value=" " selected></option>
<option value="one">item1</option>
<option value="two">item2</option>
<option value="three">item3</option>
<option value="four">item4</option>
</select><br><br>
<select name="list2" size="1"onchange="setOptions(document.menu.list2.options
[document.menu.list2.selectedIndex].value,document.menu.list3,' ');">
<option value=" " selected>Select an option</option>
</select><br><br>
<select name="list3" size="1">
<option value=" " selected>Select an option</option>
</select><br>
</div>
</form>';
?>
Drop down list
<script>
function setOptions(chosen, selbox, selbox2)
{
selbox.options.length = 0;
if (chosen == " ")
{
selbox.options[selbox.options.length] = new Option('Select an option',' ');
selbox2.options[selbox2.options.length] = new Option("Select an option"," ");
setTimeout(setOptions(' ',document.menu.list3),5);
}
if (chosen == "one")
{
showList2(selbox);
}
if (chosen == "two")
{
showList2(selbox);
}
if (chosen == "three")
{
showList2(selbox);
}
if (chosen == "four")
{
showList2(selbox);
}
//some code snipped
}
function showList2(selbox)
{
<?php
$n = 0;
$list1 = $_POST['choice'];
foreach($list[$list1] as $key => $value)
{
$key_array[$n] = $key;
$Lname[$n] = $list[$list1][$key]['name'];
$n++;
}
$jsArray = json_encode($key_array);
echo "var jsKeys = ". $jsArray . ";";
$jsArray = json_encode($Lname);
echo "var jsNames = ". $jsArray . ";";
?>
for (var i=0;i<jsKeys.length;i++)
{
var result = selbox2.options[selbox2.options.length] = new Option(jsNames[i],jsKeys[i]);
if(i == jsKeys.length-1)
{
var result = setTimeout(setOptions(jsKeys[0],document.menu.list3,' '),5);
}
}
return(result);
}
</script>
The $_POST superglobal is only set when the js function fires, ie when you choose something from the dropdown list. Otherwise remains empty.
You can check what's in the $_POST array with print_r($_POST)
Normally, I use a utility method to retrieve data from arrays:
function arrGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
This returns the value for the key or the default. Usage like:
if(arrGet($_POST, 'choice')){
//do something
}
Hope this helps...
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
that little # in $("#list1") means the id of the element should be matched.
<select name="list1" ..... change it to <select name="list1" id="list1".....>

Categories