I have been trying to make a custom form located on a separate page in my WordPress website. I ended up making a plugin that generates the form html and should post entered data in wp_usermeta. There are three radio button options, one of which is "other", that once clicked makes a textbox visible for alternative input.
The issue I have is that radio button values are not posted to wp_usermeta, only textbox input is (if entered).
Here is the html snippet for the form:
<form name="forming_the_team" method="POST" action="">
<div id="about">
A. Tell us about the team. <br/>
<input type="radio" name="team" value="club" onclick="otherCheck()" id="club"/>Club<br/>
<input type="radio" name="team" value="class" onclick="otherCheck()" id="class"/>Class<br/>
<input type="radio" name="team" value="other" id="other-radio" onclick="otherCheck()"/>Other</br>
<input type="text" name="team2" id="other-box"/><br/>
</div>
<br/>
<input type="submit" value="Submit"/><br/>
</form>
otherCheck() onclick attribute is a javascript function that makes a text box visible if "other" radio button is checked.
Here is one of the things I tried (among others) to update wp_usermeta:
<?php function handleDB() {
$user_id = get_current_user_id();?>
<script type="text/javascript">
if(document.getElementById('club').checked) {
<?php update_user_meta( $user_id, 'team', $_POST['team']);?>
}
if(document.getElementById('class').checked) {
<?php update_user_meta( $user_id, 'team', $_POST['team']);?>
}
if(document.getElementById('other-radio').checked) {
<?php update_user_meta( $user_id, 'team', $_POST['team2']);?>
}
</script>
<?php
}?>
I call handleDB() from the same page via shortcode:
function shortcodeDB() {
ob_start();
displayHTML();
handleDB();
return ob_get_clean();
}
add_shortcode('form_handle','shortcodeDB');
To summarize, text input gets posted successfully, while radio button values post NULL. What can I do to post radio button values as well.
Thank you in advance.
You can't mix client side code (javascript) and server side code (PHP) in the that way. The PHP is going to run no matter what in what you have posted. Here is a solution that should work using only PHP.
<?php function handleDB() {
$user_id = get_current_user_id();
if( 'other' == $_POST['team'] ){
update_user_meta( $user_id, 'team', $_POST['team2']);
}else{
update_user_meta( $user_id, 'team', $_POST['team']);
}
}
?>
If this doesn't work comment below and I will troubleshoot further but this should do the trick.
Related
I am working on a project that includes an search function , currently the search works fine for that i am using an dropdown and select the value .
this is code that i am using with dropdown
<div class="form-group form-group-lg form-group-icon-left search"><i class="fa fa-plane input-icon"></i>
<label>Select an option</label>
<select class="typeahead form-control" name="search">
<?php foreach($search_des as $sd) { ?>
<option value="<?php echo $sd->des_category_id;?>">
<?php echo $sd->des_category_name;?></option>
<?php } ?>
</select>
<br>
</div>
Now as per our client requirement they need to display all the items with a radio button and also they want to submit the page by clicking on the radio
. I tried to use radio button it doesnot works properly.
This is the code that ia am using with radio button.
<div class="form-group">
<label>Select an option</label>
<?php foreach($search_des as $sd) { ?>
<label>
<input class="form-control" value="<?php echo $sd->des_category_id;?>" type="radio">
<?php echo $sd->des_category_name;?></label>
<?php } ?>
<br>
</div>
while using this all items are listing correctly but all the radio buttons are checked, also i dont know how to auto submit a form using a radio button.
You'll need to use Javascript to trigger submitting the form on click.
Add an event listener to the radio button being clicked, and then trigger the form to submit when that event happens.
Something like this should work, just change the IDs accordingly.
var form = document.getElementById("form-id");
document.getElementById("radio-id").addEventListener("click", function () {
form.submit();
});
You did not give the
name
attribute
to input
<div class="form-group">
<label>Select an option</label>
<?php foreach($search_des as $sd) { ?>
<label>
<input name="search" class="form-control" value="<?php echo $sd->des_category_id;?>" type="radio"><?php echo $sd->des_category_name;?></label>
<?php } ?>
<br>
Ok, so there are multiple things to be addressed in this question.
First, as mentioned above, you need to add the name tag to your radio button.
Secondly, you need to use JavaScript to submit the form on the click event of radio button. To get the click event set up, add the class at your radio button.
Posting the answer here with the link to my Codepen.
Code
<form name="theForm">
<div class="form-group">
<label>Select an option</label>
<?php foreach($search_des as $sd) { ?>
<label>
<input class="form-control radioClass" value="<?php echo $sd->des_category_id;?>" type="radio" name="category">
<?php echo $sd->des_category_name;?></label>
<?php } ?>
<br>
</div>
</form>
JS
var classname = document.getElementsByClassName("radioClass"); // The radio button class we've added
var myFunction = function() {
document.theForm.submit(); //theForm is the name of the form.
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false); //Adding listener to the click event.
}
You can play with the code (of course PHP script has been replaced with the dummy data) at this link: https://codepen.io/akshit_ij/pen/KydVXz
Let me know if it helps.
I am trying to displaying the input fields depending upon the what outputs are coming from the database. Please share any idea or logic in this. I have more than 25 fields.
Page1.php
I have Name(Text type), Email(Email type), gender(Radio), country(Select dropdown), Address( Textarea) in the form. The user will click on check box whatever he needs from the form and click on submit then the value of the fields which he selects will store in the database.
Form page
Page2.php
Here I am displaying the fields which are selected from Page1.php but also I need input type related to which fields come from the database.
For example: In the page1 I choose Name, Email, Country and submitted the form then In page2 I have to display the output <input type="text" name="Name">,<input type="text" name="Name">,<select></select>.
I need to know what logic I have to use it. Can any one help me with the script?
Form code
<form action="" method="post">
<input type="checkbox" name="check-fields[]" value="Name">
<label>Name(Text type)</label>
<input type="checkbox" name="check-fields[]" value="Email">
<label>Email(Email type)</label>
<input type="checkbox" name="check-fields[]" value="Gender">
<label>Gender(Radio type)</label>
<input type="checkbox" name="check-fields[]" value="Select">
<label>Country(Drop down)</label>
<input type="checkbox" name="check-fields[]" value="textarea">
<label>Address(Textare)</label>
<input type="submit" name="submit" value="submit">
</form>
Storing the value in the database
if (isset($_POST['submit'])) {
// prepare and bind
$a=$_POST['check-fields'];
$elements= implode(',',$a);
$sql_elements="INSERT INTO test (elements) VALUES (?)";
$stmt = $conn->prepare($sql_elements);
$stmt->bind_param("s", $elements);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
}
Page 2
I am getting output but how can I set the input fields?
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
You're trying to create a personalized form for different users if I'm correct, meaning that you will allow a user to generate a form based on a selection of fields the user can choose from.
What you need to do is create a table called "forminputtypes" where you create a row for each different input field you can think of, and want to give the user as a choice to select from. Your table would looke like this:
Id | FieldName | Type | etc ->
-------------------------------
1 | Name | text | ...
2 | Email | email | ...
3 | Gender | radio | ...
You can add more columns in the table to store more information (think of possible values in a radio input or a dropdown).
Now at in Page1.php you select all input types from this table, and display them like you already are. However, the value of these checkboxes will be the corresponding Id value of the record in the database like so:
<input type="checkbox" name="check-fields[]" value="3">
Now when someone chooses the Gender field, you can see in your Page2.php that the user did so by matching his choice '3' to the record in the database. If you want to save this information, you can create another table called UserFormInputFields which will function as a couple table between your user table and the FormInputTypes table.
When you want to display the form in Page2.php, you simply get all the input fields the user chose by selecting on Id from the FormInputTypes table. Since you know the type of each input field (because it's a column in the table) you can display them all correctly.
If you want to do it in core PHP only.Just put if else around the html tags.If value is coming from Database then you show particular tag else nothing. You can modify your page 2 code like.
<?php
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
<form action="" method="post">
<?php if(in_array("Name",$arr)) { ?>
<input type="text" name="name" >
<label>Name</label>
<?php } ?>
<?php if(in_array("Email",$arr)) { ?>
<input type="email" name="email">
<label>Email</label>
<?php } ?>
<?php if(in_array("Gender",$arr)) { ?>
<input type="radio" name="gender" value="Male">
<input type="radio" name="geneer" value="Female">
<label>Gender(Radio type)</label>
<?php } ?>
//.............write other fiels like this.
<input type="submit" name="submit" value="submit">
</form>
I hope this helped.
Actually I am generating input fields for HTML-Form dynamically.
Now my problem is when submit the form nothing will be post to my php.
So when I am using
echo "<pre>"; print_r($_POST) ; echo "</pre>";
in my php there is an empty array.
Here is my html-form:
<form method="POST" action="../php/saveTraining.php" id="trainingForm">
<section id="mainCategory" class="hidden">
<label><input type="checkbox" name="mainCat" id="Krafttraining">Krafttraining</label>
<label><input type="checkbox" name="mainCat" id="Joggen">Joggen</label>
</section>
<section id="categoryKrafttraining" class="hidden">
<label class="subCategory"><input type="checkbox" class="subCategory">Kurzhantel</label>
<label class="subCategory"><input type="checkbox" class="subCategory">Bankdrücken</label>
</section>
<section id="categoryJoggen" class="hidden">
<label><input type="number" name="joggingKm" id="joggingKm">Kilometer</label>
<label><input type="number" name="joggingTime" id="joggingTime">Zeit</label>
</section>
<input type="hidden" id="saveTraining" name="sent" value="save">
</form>
you can ignore the 3rd section, because actually I am not working with it.
So here is the .js code where I create the additional fields:
('#'+ category +' :checkbox').off('change').change(function (event) {
console.log("YUP");
sectionID = 'sect'+ $(event.target.parentNode).text();
if (this.checked){
//append input fields
$('#'+category).append( '<section id='+sectionID+'><h5>'+$(event.target.parentNode).text()+'</h5><label><input type="number" name="saetze" id="saetze">Sätze</label>' +
'<label><input type="number" name="wiederholungen" id="wiederholungen">Wiederholungen</label></section>');
}else{
console.log("HIER");
//delete not necessary input fields
$('#'+sectionID).remove();
}
});
here is my .php connection :
<?php
$host= "127.0.0.1";
$user= "censored";
$pw= "censored";
$db= "censored";
$mysqli = new mysqli("localhost", "$db", "$user", "$pw", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
echo $mysqli->host_info . "\n";
?>
and here is the .php that get called from form submit:
<?php
include ('datenbankConnect.php');
$saetze = $_POST['saetze'];
$wiederholungen = $_POST['wiederholungen'];
echo "werte:";
echo $saetze;
echo "<pre>"; print_r($_POST) ; echo "</pre>";
?>
So when submitting the form I also get the following message from my php:
Notice: Undefined index:
Notice: Undefined index:
Maybe you could help me. It would be great!
So there is a problem with method="post". When I am using method="get" and accordingly changing the php to GET everything works fine.
So could it be possible that POST is not working for PhpStorm's integrated server?
SOLVED
The problem was that PhpStorm's integrated server have some issues with POST method. With GET everything works fine.
And guys, don´t forget to give your input types names ;)
What is output of:
echo "<pre>"; print_r($_POST) ; echo "</pre>";
If you don't have saetze in your post array you should inspect HTML code with firebug or chrome devTools to see if your javascript code is working properly.
Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}
I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name