I have searched far and wide and have not seen an answer for this. Forgive me if one exists.
I have a PHP page, in which user can generate new html select fields by pressing a button. I use Javascript to generate the new select fields. The user can then select one option from the generated select field. I need the value the user chose in PHP code below the form, to submit the form values to database.
My problem is that PHP doesn't seem to recognize the new generated select fields, which is why it won't post.
var_dump($_POST) doesn't show the new select field. I have also tried to name the new select as name="choice1[]", but that also has not posted. Choice1 is always undefined.
All of my code is on the same PHP page, apart from sql query to populate the select options.
This is what Javascript generates inside a form:
<select class="form-control" id="choose1" name="choice1">
<option value="1:x">Text</option>
<option value="2:y">Text</option>
<option value="3:z">Text</option>
</select>
This is where I try to get the value, after submit button is pressed:
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr1[0];
$tName = $arr1[1];
}
The Javascript works fine, the values are shown on the page fine. The only part not working is the post method (well, only for this specific select field. Other's work fine, as those are hard coded to html). Submit button works fine, everything else gets submitted.
My question is if there is a way for me to get the post values in PHP without reloading the page?
Or if reload is needed, how to do this without closing the form modal?
Or even more of a general question would be.. How do I do this?
EDIT:
Here is my form code. I deleted bunch of other stuff from it just to show the parts I have the problem with. If the divs are weird, it's because of that.
<form class="form-horizontal" method="post" action="">
<div class="modal-header">
<h4 class="modal-title">Change</h4>
</div>
<div class='modal-body'>
<div class='row'>
<label class="col-sm-3"> Product: </label>
<div class="col-sm-8" id="selectProd">
<!-- **This is where new select is generated** -->
<select class='form-control' id='valinta' name='choice'>
<?php
$sql0= "SELECT tuotenro, tuotenimi FROM vaateHenkilot WHERE asnro = '". $_GET['b']."' AND henknro = '". $_GET['a']."' GROUP BY tuotenro, tuotenimi";
$req = sqlsrv_query($con, $sql0) or die(print_r(sqlsrv_errors(),true));
$t = '';
while($row = sqlsrv_fetch_array($req)) {
$t = array(
array (
'nro' => $row['tuotenro'],
'nimi' => $row['tuotenimi'],
)
);
$tuotteetIN = array_column($t, 'nimi', 'nro');
foreach($tuotteetIN as $key => $value) {
?>
<option value="<?php echo $key ?>:<?php echo $value ?>"><?php echo $value ?></option>
<?php
}
}
?>
</select>
<br>
</div>
<div class="col-sm-1">
<button type='button' class='btn' onclick='addSelectBox()'>+</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="saveButton">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
<?php
if (isset($_POST['saveButton'])) {
$choice = $_POST["choice"];
$parts = $choice;
$arr = explode(':', $parts);
$tNum = $arr[0];
$tName = $arr[1];
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr[0] . ', ' . $arr1[0];
$tName = $arr[1] . ', ' . $arr1[1];
}
*Here is the sql query*
}
?>
I have another select there, which has the same values. That one works well.
I'll add the Javascript here that creates the new select, as well.
<script type="text/javascript">
var j = 0;
function addSelectBox (){
if (j < 3){
var parentDiv = document.getElementById ("selectProd");
var selectElement = document.createElement ("select");
j++;
selectElement.setAttribute("class", "form-control");
selectElement.setAttribute("id", "choose" + j);
selectElement.setAttribute("name", "choice" + j);
var tuotteet = '';
$.ajax({
type: 'GET',
url: 'productHelp.php?asi=<?php echo $asnro; ?>&hen=<?php echo $henro; ?>',
data: tuotteet,
datatype: 'json',
cache: false,
success: function (data) {
var tnimi = data.split(";");
for (var i=0;i < tnimi.length -1;i++){
var tnro = tnimi[i].split(",");
var option = new Option (tnro[1], tnro[0]+":"+tnro[1]);
selectElement.options[selectElement.options.length] = option;
}
}
});
parentDiv.appendChild (selectElement);
parentDiv.appendChild(linebreak);
}
}
</script>
Turns out the problem was as "stupid" and simple as I figured it had to be.
Taking the modals with the functionality out from the table structure made it work fine.
Good to learn something new about formatting everyday!
Related
just a fair warning: I'm a HTML, PHP and JavaScript noob.
I wrote code to get multiple selection boxes, where the selectable content from the second box is dependent on the
selection of the first box.
So like:
Brands: if Asus is selected the next box: and the last box is prime is selected:
Asus Prime B560
MSI Plus Z590 etc.
This has to be expendable to newer models, brands etc.
The Code I have so far:
(hersteller means manufacturer)
index.html
<!DOCTYPE html>
<head></head>
<body>
<form name="form1" id="form1" action="redir.php">
Hersteller: <select name="hersteller" id="hersteller">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Modell: <select name="model" id="model">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Chipset: <select name="chipid" id="chipid">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
<input type="submit" value="weiter">
<script>var subjectObject = {
"Asus": {
"Prime": ["B560", "Z490", "Z590", "Z690"],
"ProArt": ["Z490"],
"ROG": ["Z690 ITX"]
},
"MSI": {
"Torpedo": ["Z490", "Z590", "Z690"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("hersteller");
var topicSel = document.getElementById("model");
var chapterSel = document.getElementById("chipid");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
chapterSel.length = 1;
topicSel.length = 1;
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() {
chapterSel.length = 1;
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}</script>
</form>
</body>
redir.php
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
if ($hersteller = "Asus") {
if($model = "Prime"){
if($chipid = "B560"){
header("Location: /driver_sites/Asus_Prime_B560.html");
}
}
exit();
}
//elseif ($items = 'Item2') {
//header("Location: item2.php");
//}
?>
I want to process the data selected and redirect to a specific site. For example
if the user selects "Asus" -> "Prime" -> "B560" and clicks on "weiter" (submit), it should redirect him to
a page like Asus_Prime_B560.html
How can this be done?
Thanks in advance :)
I tried multiple ways in PHP but nothing seems to work and my knowlege is limited.
Also, I searched what feels like the entire internet but to no avail.
I hope I understood your problem, what about changing your "redir.php" file as follows:
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
header("Location: /driver_sites/".$page);
What this does is build the "page filename" based on the inputs and just redirect to it. Let's say that the user selected following values:
$hersteller = 'Asus';
$model = 'Prime';
$chipid = 'B560';
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
$page is now => Asus_Prime_B560.html
This example implies that all pages have the same format HERSTELLER_MODEL_CHIPID.html
Edit:
Based on your comment I will add some info
When you see some URL containing ?some=thing&foo=bar the part after the ? (question mark) is called query string. This query string parameters can be accessed by PHP using the $_GET superglobal (i.e. to read param foo i can do
$foo = $_GET['foo']; //$foo now contains "bar"
On the other end, if the form has been submitted using the POST method (<form method="post" ....>) the the data can be accessed using the $_POST superglobal
$something = $_POST['paramNam'];
I have a page with 2 forms. The first form (below) is just a drop down list of values which controls what is loaded into the 2nd form. The 1st form submits to the same page.
Without making the 1st form (on submit) open a 2nd page with the 2nd form, is there a way (on load) to get the currently selected value of the drop down for use in the second form? This is only a problem on the initial page load. Thanks.
<form action="/get_gs_link_status.php" method="post" onchange="submitForm()">
<select name="select_PM" id="select_PM">
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['PM']}\">";
echo $row['PM'];
echo "</option>";
}
?>
</select>
</form>
<p id="PID_value"></p>
<script>
function submitForm() {
var x = document.getElementById("select_PM").value;
document.getElementById("PID_value").innerHTML = "You selected: " + x;
}
</script>
Add an onload handler that calls submitForm().
<p id="PID_value"></p>
<script>
function submitForm() {
var x = document.getElementById("select_PM").value;
document.getElementById("PID_value").innerHTML = "You selected: " + x;
}
window.addEventListener("load", submitForm);
</script>
This question already has an answer here:
Populating a select box using JQUERY, AJAX and PHP
(1 answer)
Closed 6 years ago.
I have a PHP form where a dropdown is populated with values from a database table.
$options_demande['orderBy'] = array('id_produit' => 'ASC');
$options_demande['items'] = array('produit');
$data['id_produit'] = $this->produit_model->getListCombo('*',null,$options_demande,'Sélectionner un produit');
$options_demande['orderBy'] = array('id_abonnement' => 'ASC');
$options_demande['items'] = array('abonnement');
$data['id_abonnement'] = $this->abonnement_model->getListCombo('*',null,$options_demande,'Sélectionner un abonnement');
The getListCombo method :
public function getListCombo($select = '*', $conditions = array(), $optional = null, $first_line = null)
{
$dropdown = array();
if ($select != null)
$this->db->select($select)->from($this->table);
if (isset($conditions['where']))
$this->db->where($conditions['where']);
if (isset($conditions['where_in']))
$this->db->where_in($conditions['where_in']);
if (isset($conditions['where_or']))
$this->db->or_where($conditions['where_or']);
if (isset($conditions['like']))
$this->db->like($conditions['like']);
if (isset($conditions['like_or']))
$this->db->or_like($conditions['like_or']);
if (isset($optional['orderBy']))
foreach($optional['orderBy'] as $order => $val)
$this->db->order_by($order,$val);
$rs = $this->db->get()->result_array();
if (isset($first_line))
{
if (is_array($first_line))
$dropdown[$first_line['k']] = $first_line['v'];
else
$dropdown[''] = $first_line;
}
foreach($rs as $item){
$liste = null;
foreach($optional['items'] as $item_liste){
$liste .= $item[$item_liste]." ";
$dropdown[$item['id_' . $this->table]] = $liste;
}
}
return $dropdown;
}
The thing is that I want an other dropdown to be populated with specific values of an other table.
The code of my dropdown :
<div class="form-group">
<label class="col-md-2 control-label" for="id_produit"><?php echo lang('produit'); ?><span class="required"> * </span></label>
<div class="col-md-4">
<?php echo form_dropdown('id_produit', $id_produit, null,'class="form-control" required="required"')?>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="id_abonnement"><?php echo lang('abonnement'); ?><span class="required"> * </span></label>
<div class="col-md-4">
<?php echo form_dropdown('id_abonnement', $id_abonnement, null,'class="form-control" required="required"')?>
</div>
</div>
I think I have to use some javascript, but I don't know how to do that.
At the moment the other is populated with all the values of the other table, but I'd like for example that for a specific value of the first dropdown, the other is populated with the values of the other table where "type_abonnement" = 1. Or 2 for an other value.
Yes, you will need to use JavaScript to achieve this.
There's hundreds of topics on this already, check out: Populating a select box using JQUERY, AJAX and PHP for example.
I am trying to make a country -state selector in Jquery which should submit values in db using PHP. Here is the script:
<script type="text/javascript">
var state_arr=new Array("Jammu and Kashmir","Delhi","Uttar Pradesh","Tamil nadu","Maharashtra","Karnataka","West Bengal","Punjab","Haryana");
var s_a = new Array();
s_a[0]="";
s_a[1]="Srinagar|Jammu";
s_a[2]="New Delhi";
s_a[3]="Lucknow|Kanpur|Ghaziabad|Noida|Varanasi";
s_a[4]="Chennai";
s_a[5]="Mumbai|Pune|Aurangabad|Thane";
s_a[6]="Bangalore|Mysore";
s_a[7]="Kolkata";
s_a[8]="Chandigarh|Mohali";
s_a[9]="Gurgaon|Chandigarh";
function print_state(state){
//given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(state);
option_str.length=0;
option_str.options[0] = new Option('Select State','');
option_str.selectedIndex = 0;
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
function print_city(city, selectedIndex){
var option_str = document.getElementById(city);
option_str.length=0;
option_str.options[0] = new Option('Select City','');
option_str.selectedIndex = 0;
var city_arr = s_a[selectedIndex].split("|");
for (var i=0; i<city_arr.length; i++) {
option_str.options[option_str.length] = new Option(city_arr[i],city_arr[i]);
}
}
Here is the PHP code which displays the selector:
<?php if (!isset($_POST['submit_val3'])) { ?>
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state"></select>
<br />
City:
<select name ="city" id ="city"></select>
<script language="javascript">print_state("state");</script>
<input type="submit" name="submit_val3" value="Submit" />
<?php } ?>
Here is PHP code for submission:
if(isset($_POST['submit_val3']))
{
$city=$_POST['city'];
$state=$_POST['state'];
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME);
$query="UPDATE register_emp SET state='$state',city='$city' WHERE ID = '" . $_SESSION['ID'] . "'";
mysql_query($query,$dbc) or die('query failed');
mysql_close();
}
My problem is that on clicking on Submit button,no values are being submitted to database.Where am I wrong here ?
Please add a form tag and action , thats why its not submitting to php page.
<?php if (!isset($_POST['submit_val3'])) { ?>
<form method="post" action="yourphppage.php"> <!-- form tag and action page -->
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state">
City:
<select name ="city" id ="city">
<script language="javascript">print_state("state");
<input type="submit" name="submit_val3" value="Submit" />
</form>
<?php } ?>
I have a line of HTML drop down lists, and whenever the user selects one of the options, it calls a jQuery function through a class which submits the form.
<form id="workorderform" action="saveworkorder.php" method="post">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
the savevalueonchange class calls
$(".savevalueonchange").change(function() {
autoSave();
});
which then calls
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
}
}
which posts the information to the saveworkorder.php
//remove existing chargecodes
$sql = "DELETE FROM workorderchargecodes WHERE compresscoid = '".trim($_REQUEST['formid'])."'";
mssql_query($sql, $dbconn);
//now save chargecodes
$code_prefix = 'code_';
foreach($_POST as $thisPostKey => $thisPostValue) {
if((substr($thisPostKey, 0, strlen($code_prefix)))==$code_prefix) {
if(trim($thisPostValue)!=''):
$exists=false;
$sql = "SELECT * FROM workorderchargecodes WHERE compresscoid='".trim($_REQUEST['formid'])."' AND code='".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."'";
$res = mssql_query($sql, $dbconn);
while($arr = mssql_fetch_assoc($res)){
$exists=true;
}
if($exists==false){
$sql = "INSERT INTO workorderchargecodes (
compresscoid,
code,
time
) VALUES (
'".trim($_REQUEST['formid'])."',
'".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."', '".$thisPostValue."'
)";
mssql_query($sql, $dbconn);
}
endif;
}
}
As you can see, I am selecting the code from the database before I insert it into the database and am somehow still getting duplicate charge codes. I have messed with this for a few months now, and it still keeps happening.
Any ideas?
Try to add return false; in your autosave(), like this :
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
return false; // add here
}
}
It will prevent to submit twice.
<form id="workorderform" action="saveworkorder.php" method="post" onsubmit="return false;">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
use this form
it use obsubmit="return false;"