Ive saved form data with ajax and php, reusing the data from the database.
However the way I am approaching this is different, there is no database, so some insight would be great.
I am emailing form data, all the data is just simple checkboxes, the values are either 0 or 1. When the user refreshes the page id like to keep the checked values.
I guess without a database I would need to use cookies, and the only way to avoid cookies would be ajax and a database (strictly my logic, not sure if true), this is why I am asking, I just want a simple solution.
Form snippet:
<input name="sharks" type="hidden" value="0">
<input name="sharks" type="checkbox" value="1" id="sharks" '.$VALUE ? ' checked="checked"' : ''.'>
The php part of that input is shaky, Id like to question whether the value is 0 or 1, if its 1 then its checked if its 0 then empty.
Getting it from the database would be easier but not so sure since there is no database, Im guessing cookies would come into place.
Sorry if this last part is shaky but im a little unsure and dont know where to look.
Using Sessions:
session_start();
if(isset($_POST['submit'])) {
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form
<form action="<?php the_permalink(); ?>" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<?php
if ($_SESSION['value'] == 1) {
$checked = 'checked="checked"'; }
?>
<li>
<input name="personalization_result[memory_0]" type="hidden" value="0">
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" value="0">
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_2]" type="hidden" value="0">
<input name="personalization_result[memory_2]" type="checkbox" value="1" id="personalization_result_memory_2" <?php $checked ?> >
</li>
This code stores the data in a session:
<?php
session_start();
if(isset($_POST['submit']))
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
}
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
print ' checked="checked"';
}
print ">";
?>
<br>
<input type="submit" name="submit" value="Save" />
</form>
Worked for me, keeping the checkbox checked after I closed and opened the browser again. After some testing I added a rather complex if to avoid the undefined variable notice. Now the set part seems robust.
You can either use session or cookie. Basically you will access using $_COOKIE or $_SESSION. I would rather say that this is easier than using a database.
For cookies have a look at setcookie (http://www.php.net/setcookie)
For sessions: http://php.net/manual/en/book.session.php
I would use local storage or session storage, this is a client side memory storage location that persists even if the page is refreshed, it is integrated into html5.
Here is a nice tutorial about it:
http://www.w3schools.com/html/html5_webstorage.asp
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Persist checkboxes 1</title>
<script>
window.jQuery || document.write("<script src='jquery-.1.1.js'><\/script>");
</script>
<script>
$(document).ready(function()
{
$('#me').click(function()
{
var seloption = $('input[type="checkbox"]:checked');
if (seloption.length > 0)
{
var abc = seloption.length + "checked \n";
//alert(abc);
i = 0;
seloption.each(function()
{
abc = abc + $(this).text(seloption[i]) + "<br>";
}
);
$('#msg').html(abc);
}
}
);
}
);
</script>
</head>
<body>
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<div>
<label for="option4">Option 4</label>
<input type="checkbox" id="option4">
</div>
<div>
<label for="option5">Option 5</label>
<input type="checkbox" id="option5">
</div>
<div>
<label for="option6">Option 6</label>
<input type="checkbox" id="option6">
</div>
<div>
<label for="option7">Option 7</label>
<input type="checkbox" id="option7">
</div>
<div>
<label for="option8">Option 8</label>
<input type="checkbox" id="option8">
</div>
<div>
<label for="option9">Option 9</label>
<input type="checkbox" id="option9">
</div>
<button type="button" id="me">Submit</button>
<div id="msg">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
$(":checkbox").on("change", function() {
var checkboxValues = {};
$(":checkbox").each(function() {
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, {expires: 1, path: '/'});
});
function repopulateCheckboxes() {
var checkboxValues = $.cookie('checkboxValues');
if (checkboxValues) {
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
</script>
</body>
</html>
Related
Actually I want to append to div only checked values but it is appending unchecked values also. I used in_array function to check conditions if value is checked means append only checked value not all but it is appending all the values but its checking only value please somebody help me out..
Below is HTML and PHP code:-
<div class="flDrop">
<div class="flDropDiv">
<?php
foreach ($filter_group['filter'] as $filter) { ?>
<?php
if(in_array($filter['filter_id'],$filter_category))
{ ?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>" checked> <?php echo $filter['name'];?>
<?php } else {?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>"> <?php echo $filter['name'];?>
<?php }?>
<?php }?>
</div>
</div>
Jquery code:-
setTimeout(function(){
var filter_len = $('input[name^=\'filter\']:checked').length
// alert(filter_len);return false;
$("#auto_filter_values").empty();
if(filter_len>1){
/*$("#auto_filter_values").append('<div class="afr clearall">Clear All filters</div>');*/
}
$('input[name^=\'filter\']:checked').each(function(element) {
$("#auto_filter_values").append('<div class="afr fSbtn" id="fSfilter'+this.value+'" data-val="'+this.value+'">'+$(this).parent().text().replace(/\(([A-Za-z0-9 ]+?)\)/, '')+'<span class="fSc"></span></div>');
});
}, 100);
Working fine with some small changes (an example code):-
setTimeout(function(){
$.each($("input[name='filter[]']:checked"), function(){ //change here
$("#auto_filter_values").append('<div class="afr fSbtn" id="fSfilter'+this.value+'" data-val="'+this.value+'">'+$(this).attr('data-id')+'<span class="fSc"></span></div>'); // changes here
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flDrop">
<div class="flDropDiv">
<input name="filter[]" type="checkbox" value="1" data-id ="Black" checked> Black <br>
<input name="filter[]" type="checkbox" value="2" data-id ="Black">Red<br/>
<input name="filter[]" type="checkbox" value="3" data-id ="Pink" checked>Pink<br/>
<input name="filter[]" type="checkbox" value="4" data-id ="Blue">Blue<br/>
</div>
</div>
<div id = "auto_filter_values" style ="margin-top:30px;"></div>
Note:- you need to add data-id attribute with you color name on check-boxes and then you can get easily
Im trying to save $_SESSION data to keep checked values on page refresh, I have some code written up but I am missing a piece.
Session Code:
session_start();
if(isset($_POST['submit'])) {
//user posted variable
$checks = $_POST['personalization_result'];
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form Code:
<form action="" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<li>
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" />
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" class="<?php echo $_SESSION['value']['memory_1'] ?>" value="0" />
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" />
</li>
//There are many checkboxes, this is just two for demo purposes
<input class="submit" type="submit" value="Send" />
</form>
For testing I am echoing $_SESSION['value']['memory_0'] && $_SESSION['value']['memory_1']inside the hidden input, they return properly, if the input is checked the class is 1, if it's unchecked the class is 0.
I am not sure the best way to say if it = 1 then echo checked="checked"
My shotty attempt:
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php if($_SESSION['value']['memory_0'] = 1) {echo 'checked="checked"';} ?> />
This returns an error "Cannot use a scalar value as an array", that and I dont like how thats written up.
So with all the given information, whats the best way to write if my value = 1 return checked="checked"?
This will make your PHP much cleaner and scalable:
Use this function at the top:
session_start();
function checkbox($id)
{
$isChecked = '';
if (isset($_SESSION['value']['memory_'.$id]))
{
$isChecked = ($_SESSION['value']["memory_".$id] == 1) ? 'checked="checked"' : '';
}
echo '<input name="personalization_result[memory_'.$id.']" type="checkbox" ';
echo 'value="1" id="personalization_result_memory_'.$id.'" ';
echo $isChecked.' />';
}
and then instead of writing out <input ... <?php ... ?> ... /> for every single checkbox, just use
<?php checkbox(0); ?>
<?php checkbox(1); ?>
Your short attempt has an error:
instead of <?php if($_SESSION['value']['memory_0'] = 1) try <?php if($_SESSION['value']['memory_0'] == 1)
Ok here is my problem, and all of my 'dirty' code. This isn't my production code but just trying to make it work at the moment.
Basically what I need is when a user selects the Not Ok radio button it displays the textarea for that unique set which it doesn't do right now when I select Not Ok it gives the textarea's for all the entries which right now is about 13 sets of questions that get generated dynamically from a mysql database at the moment. I have a feeling it has to do something with unique id's that are either in the wrong place in my code now, or just simply aren't there at all. Any help is appreciated greatly.
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT * FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;">
<fieldset data-role="controlgroup">
<legend><?php echo $q_title; ?>:</legend>
<input type="radio" name="help[]" id="checkbox-1a" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$(":radio:eq(1)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$(":radio:eq(0)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
<fieldset data-role="fieldcontain">
<label for="<?php echo $q_title; ?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_a[]" id="<?php echo $q_title; ?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
The other 2 answers are ways to fix your issue. As a side, here is possibly why it is happening. When you are using -
$(":radio:eq(1)").click(function()
$(":radio:eq(0)").click(function()
You are using a click listener that just checks for if 'any' radio button with that index position was clicked on your page. So any button with 1 index position will make every $(":radio:eq(1)").click(function() execute.
Edit -
You would want to change your radio button ids, as (1) they will not be unique as you repeat them with each while() loop, and (2) you could use it to check if that specific radio buttton was clicked.
Try changing it to -
...
<input type="radio" name="help[]" id="checkbox-1a-<?php echo $q_id; ?>" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a-<?php echo $q_id; ?>" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$("#checkbox-2a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$("#checkbox-1a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
The easiest way that I have found to show hide elements based off of radio values is to serve up an onchange event based on the id of the element (which you already have). In your case, since you only have two radios based off the same name, the easiest way is a simple if/else statement. Something like:
<script type="text/javascript">
$(function(){
$('#checkbox-1a').change(function(){
if($(this).attr('checked')){
$('#hidden-text-<?php echo $q_id;?>').hide(500);
}else{
$('#hidden-text-<?php echo $q_id;?>').show(500);
}
});
});
</script>
Where we state when #checkbox-1a is changed: if the element is checked (selected), then do something (in your case hide something), otherwise do something else (in your case show something).
Try something like:
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT id,title FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;" class="groupings">
<fieldset data-role="controlgroup">
<legend><?=$q_title?>:</legend>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-1a" value="Ok" />
<label for="checkbox-<?=$q_id?>-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-2a" value="Not Ok" />
<label for="checkbox-<?=$q_id?>-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?=$q_id?>" class="hiddenText" style="display:none;">
<fieldset data-role="fieldcontain">
<label for="<?=$q_title?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_<?=$q_id?>_a[]" id="<?=$q_title?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
<script>
$(document).ready(function(){
$(".groupings input:radio").click(function(){
if (this.value == "Ok") {
$(this).parent().next('.hiddenText').show(500);
} else {
$(this).parent().next('.hiddenText').hide(500);
}
});
});
</script>
This is untested, but the script only needs to be declared once and it will apply to the rest relative to the radio button.
I am trying to make a small form that lets the user pick one element from 3 different radiobutton lists to set one element as the users active element (that will be stored to MySQL). Somehow along the way it does not work and I can not seem to figure out why, perhaps someone of you can see what I did wrong?
HTML:
<form name="activeForm1" method="post">
<fieldset data-role="controlgroup">
<div class="ui-radio">
<input type="radio" name="active" value="1" id="1">
<label for="1"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="2" id="2">
<label for="2"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="3" id="3">
<label for="3"></label></input>
</div>
</fieldset>
<div data-role="footer">
<input type="submit" href="#" onclick="setActive(1)"/>
</div>
</form>
JavaScript / Ajax call
function setActive(formid)
{
$.ajax(
{
type:'POST',
url:'active.php',
data:$('#activeForm'+formid).serialize(),
success:function(response)
{
}
}
);
}
PHP code:
session_start();
include('connectToDb.php');
$id = $_SESSION['id'];
if (isset($_POST['active']))
{
$formValue = $_POST['active'];
mail('my#mail.com','Test',$formValue,'From: dummy#mail.com');
mysql_query(/* UPDATE MySQL */);
header("Location: main.php");
}
else
{
mail('my#mail.com','Test','No data recieved!','From: dummy#mail.com');
}
So it works up until the if (isset($_POST['active'])) but then mails me that no data was recieved. I already have 2 similar forms on the same page and they are way bigger and has no problems running. Can't figure out what I did wrong here.
Wrong code :
data:$('#activeForm'+formid).serialize(),
#activeForm is not an id, it is the name of the form tag,
Correct the form tag to,
<form name="activeForm1" id="activeForm1" method="post">
Replace following line
data:$('#activeForm'+formid).serialize(),
with
data: $('form[name="activeForm'+formid+'"]').serialize(),
change
<input type="submit" href="#" onclick="setActive(1)"/>
to
<input type="button" href="#" onclick="setActive(1)"/>
and then it should work
banging my head against the wall for something seemingly dead simple.
Here it is:
<html>
<head></head>
<body>
<form method="post" action="action.php">
<div><input type="checkbox" name="test" value="Newspaper"> <span >Newspaper</span></div>
<div><input type="checkbox" name="test" value="PC"> <span >PC</span></div>
<div><input type="checkbox" name="test" value="Home"> <span >Home</span></div>
<div><input type="checkbox" name="test" value="Dont_know"> <span >dnunno</span></div>
<input type="submit" name="Submit" value="send">
</form>
</body>
</html>
But when I select more then one option. I see in my print_r($_POST); statement only the last selected option in stead of all selected options.
How should I deal with this?
update:
I checked the rest of my code and i saw that this is done by some JavaScript.
else if (aform.validatorArr[i][4] == "checkbox") {
var fvs = "";
eval("var chkbArray=aform." + aform.validatorArr[i][1] + ";");
if (aform.validatorArr[i][2] == "cb_true") {
for (k = 0; k < chkbArray.length; k++) {
if (chkbArray[k].checked) {
fvs += chkbArray[k].value;
console.log(fvs);
}
}
if (fvs == false) {
s += aform.validatorArr[i][3] + "\n";
}
}
}
That's why the [] is not added in my html. But how could I modify this code so that it will take all options?
Put [] after the name:
<input type="checkbox" name="test[]" value="Newspaper">
See PHP FAQ for more details.