First of, I'm new to ajax and Java Script.. I have spend days solving this problem, but I still haven't figured it out. I have read through threads with similar problems but I still can't get it right. So here goes;
Quite simple I want post the checked value from from one of three radio buttons. All I get though is only the value of the first radio button..
I have tried several things, but I stripped down the code so it might be easier see where the problem is :-)
The ajax
<script type"text="" javascript"="">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var svar = $('#svar').attr('value');
var date = $('#date').attr('value');
var email = $('#email').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "svar="+ svar + "&email=" + email + "&date=" + date,
success: function(){
$('form#submit').hide();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
The form
<form id="submit" method="post" name="submit" action="">
<fieldset>
<legend>Dagens spørgsmål: <? echo $row['question'];?></legend>
<br>
<input type="radio" name="svar" id="svar" value="1"><? echo $row['opt1'];?>
<br>
<input type="radio" name="svar" id="svar" value="2"><? echo $row['opt2'];?>
<br>
<input type="radio" name="svar" id="svar" value="3"><? echo $row['opt3'];?>
<br>
<input name="email" id="email" type="hidden" value="<? echo $email ?>" />
<input name="date" id="date" type="hidden" value="<? echo $date ?>" />
<br><br>
<button type="submit" class="button positive"> <img src="img/tick.png" alt=""> Svar på dagens spørgsmål </button>
</fieldset>
</form>
Ajax.php
<?php
include ("dbc.php");
// CLIENT INFORMATION
$email = htmlspecialchars(trim($_POST['email']));
$date = htmlspecialchars(trim($_POST['date']));
$svar = htmlspecialchars(trim($_POST['svar']));
//stuff from answers
mysql_query("INSERT INTO answers
(`email`,`day`,`answer`)
VALUES
('$email','$date','$svar')") or die(mysql_error());
?>
Hope one you of you smart guys have a solution.. because this thing i driving me crazy
You have several problems.
First, your HTML is invalid. An ID must be unique, so each radio button must have its own ID. You associate a group of radio buttons by giving them the same NAME. (Having a unique ID then lets you associate a LABEL with each one using the FOR attribute which increases accessibility by making it easier for screen readers and providing bigger click targets).
Second, the value of a radio button is fixed. The question is "Is it successful or not?" and that is determined by seeing if it is checked or not. If you were doing this manually, you would have to loop over each radio button in the group until you found one that was checked (or use a selector that matched only the checked ratio button (:checked)).
Third, you are building your form data by mashing together strings without making sure the data is URL safe (with encodeURIComponent).
The solution is to forget about doing all this manually and just use the jQuery serialize method on the form.
First: you use the same id for several elements. ID-s should be unique, and you should address your elements with class name or other means. So instead of
$('#svar')
yous should use
$('input[name=svar]')
to reference the group of checkboxes.
Second: There is a slight mistake here:
$('#svar').attr('value');
is the value of the first radio button's value attribute, while
$('input[name=svar]:checked').val();
would give you the value of the checked radio button in the group you are selecting with input[name=svar].
Edit: thx #Quentin for pointing out my error.
First thing to know is id should be unique in a html document.
What makes attributes of type ID special is that no two such
attributes can have the same value;
[Quoted from css2 selector docs]
You have assigend same id to three radio buttons.
Now when you use var svar = $('#svar').attr('value');, only the first radio button will get selected. So, irrespective of radio button selected, only the first radio buttons value you will get.
Now, if you want to get the radio button selected you have to use jQuerys :checked selector.
Related
<script>
function refreshPage()
{
document.forms[0].submit();
}
</script>
<?php
foreach($values as $value)
{
?>
<input type = "checkbox" name = "food[]" value = "<?php echo($value['dinner']);?>">
<?php
}
?>
<button name = "pass" onClick = "refreshPage()">refresh</button>
so I have n amount of check box (depending on how many values user has)I want to keep them the check box check after the page refresh (by clicking on refresh button). I tried searching and saw similar form but the answer did not work for me.
For example the most popular answer was:
<input type="checkbox" name="txtCheck" value="your value"
<?php if(isset($_POST['txtCheck']))
echo "checked='checked'"; ?>
/><br />
this had two problem after i hit the refresh button value would not be save until i hit it twice to save(i want it to save after one click. Also sometime it save after one click but if i hit the refresh 3 time values are lost I want it to be save no matter how many time user refresh)
the second problem was it check all of the box would be check. I only want to keep the one user has check to be save.
I looked at various other possible solution but nothing worked
so if you could please help much would be appreciated. Also I need the value to be kept. I am using the checkbox value somewhere else
Edit something like this but for my array food[]. This only works for invidiual values
<input type="checkbox" name="small" class="checkbox" <?php if
($_POST['small']) echo 'checked'; ?> /> Small
I'm stuck here.
I have a 'working' function below (for each PHP array row, I"m creating a div with a form. The form has an empty input, a '+' button, and a submit button).
Using the first form/div, if I click the '+' button it adds an input field every time up to 10, which is exactly what I want.
However, when I do this on the 2nd, 3rd, or 4th form it adds inputs, but all of them to the first form. So if I click the '+' button on form 2, it adds an input to form 1. I know this has to do with having a non-unique button id and carrying that through my form inputs but I'm totally stuck on what to do here.
I need each form/div to have it's own independent fields, '+' button and submit button. Reason being, I'm going to add an AJAX call to the submit button that will submit any added input values for that given form (using the ticker ID given here `
`<?php echo $ticker['ticker'] ?>``) .
How can I fix this functionality to work for as many divs/forms as I have at any given time?
<div class="row">
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
</div>
<script type="text/javascript">
var maxItems = 1;
function moreItems(button) {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$($(button).sibling('br')[0]).insertBefore($(button));
$($(button).sibling('label')[0]).insertBefore($(button));
$($(button).sibling('input:text')[0]).insertBefore($(button));
maxItems++;
}
}
</script>
Tom, the id attribute for an HTML element needs to be unique, always make sure to use unique id's, if you want to do something for elements that are similar in most ways, use class, on a side note to solve your problem:
Also change your Html to this (pass the button into the function)
Also I changed your id to a class as moreItems_add and removed the id entirely:
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
//Accepts the button object
function moreItems(button) {
//Instead of using a global iterator, grab the number of siblings of input type text
const currentInputs = $(button).siblings('input:text').length;
//Now use this variable to check if we hit the max of ten
if(currentInputs < 10){}
replace these lines:
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
with these lines:
//$(button) refers to the button which was clicked
//.siblings() will check the node structure for element(s) with the given selector on the same level as the button
//pass the jquery object of the button which was clicked into insertBefore()
//Pass the newly created object into the line of code before calling .siblings
//These 2 are inserting the new label and input
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
//Insert a line break so that the next label and input are on new line
$('<br/>').insertBefore($(button));
You can't use the same ID to reference different DOM elements, use classes or an ID with a postfix.
If you are calling the JavaScript function to apply to a specific form you should instead call a function with a class name that applies to all of your forms. Instead of using an ID use a class
The ids have to be unique. How about if you "build them" by appending ticket number?.
Something like
id="<? php echo ("Items".$ticket) ?>". Then you can get the element's id in the js, and insertBefore as appropriate.
For the button, it would be something like this:
<button type="button" id="<?php echo "moreItems_add".$ticker ?>" onclick="moreItems(this);">+</button>
Similarly for the form element:
<form id="<?php echo "Items".$ticker ?>" method="post">
This will give each form element and each button element a unique id. --edit->- The idea being you could use that id in the js instead of #moreItems_add here'<br/>').insertBefore("#moreItems_add"); (from the original iteration of the post). That said, I hadn't groked that no object was being sent to the function (ie this here moreItems(this); and button here function moreItems(button). (And on top of all that, jquery is, ahem, not my best thing). The bottom line is: if you need an unique id for the button in the javascript, you will find it now at button.id.
Consider the following form:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo">
<input type="checkbox" value="1" name="foo">
</form>
When submitting the form, the URL ...?foo=0 will be requested if the checkbox is not checked. If the checkbox is checked, the URL ...?foo=0&foo=1 will be requested. In PHP, query string arguments override any previous arguments with the same name, so foo will have the value 1 in the PHP script handling the latter request.
What is the best way to obtain the value foo would have in the PHP script using JavaScript, when not knowing anything about the form? In theory, there could be an arbitrary number of inputs named foo of different types, and I would like to know the value that foo would have in the PHP script handling the request if the form was submitted.
As I understand it, the answer is the value of the last enabled input element named foo. By enabled, I mean that the input element is not disabled and that it is not a button (the button's name and value are not added to the query string unless the button is used to submit the form) or an unchecked checkbox or radio button.
Maybe there is an easy way to get this value using jQuery?
Edit
Loads of people suggest that I rename the input elements to foo[] or similar. I guess I was not clear enough that I actually want all the input elements named foo, and to only receive one of the values in the php script.
My questions is how to determine which value the php script will receive using JavaScript.
use this:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
and in PHP, use:
$params = $_GET['foo']; //params would hold array
it would be good to use.
You can do a loop on the global variable $_GET
foreach($_GET as $key=>$val) {
echo "key = $key , val = $val";
}
if you have multiple inputs with the same name you will need to append []to the name so you can get all the values as a array
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
to get the values in jquery you do the following:
$('input[name="foo[]"]').each(function(){
console.log($(this).val());
});
if you only want one value of foo but you have multiple elements with that name you will need to change your logic to using radio buttons
This is really bad design. You should check checkbox state in your php (backend) code. Get rid of the hidden input:
<form method="get" enctype="multipart/form-data">
<input type="checkbox" value="1" name="foo">
</form>
and put this in your php code:
if (isset($_GET['foo'])) {
$foo = 1;
} else {
$foo = 0;
}
If you want to use javascript, you can try this on form submit:
var checkboxValue = $("input[name='foo']").prop("checked");
checkboxValue would be true or false depending on checkbox status.
EDIT 3: Ahha... some progress. The problem was actually in some code below the divs that I left out (updated HTML below to reflect). The second div contains a "required" input, so simply changing the div to display=none via javascript doesn't actually make the page entirely ignore the hidden Div. So a slight change to the angle of my question - how would I adjust the code below to completely ignore the hidden div, so that the required field is not read?
EDIT 2:I have tried removing the 2nd block of JS code below and inserting the dynamic PHP code directly into the input and div tags to change the display - still no luck.
EDIT 1: Just to confirm, the solution to a similar question doesn't work in this case: Auto checked radio buttons and php form processing - How to avoid blank field? it seems that the Chrome team have made changes in later versions that make this solution redundant.
A user on the website can select either Points or Stamps - I get the value from the Database via PHP and the form should have the relevant radio button checked and only show the Div related to that radio button.
Everything works fine, however, unless I manually change the radio button it will not let me POST the form i.e. I cannot post with value selected automatically from the DB - it seems a similar problem to this (Chrome Browser Ignoring AutoComplete=Off) - but no matter what I do with Chrome autocomplete it doesn't work. Also the page is recognising the radio as checked because it shows my dot in the right place. (EDIT 3: still unsure why this works in Mozilla but not Chrome - but latest Edits make this less important)
Heres my JS that shows the right Div if a radio button is changed:
$(function () {
var $divs = $('#option > div');
$('input[type=radio]').change(function() {
$divs.hide();
$divs.eq( $('input[type=radio]').index( this ) ).show();
});
});
This JS sets the correct radio button based on DB and shows the correct div when the page loads:
$(function() {
var $radios = $('input:radio[name=selection]');
var $type = "<?php echo $type; ?>";
if($type === 'points') {
$radios.filter('[value=points]').prop('checked', true);
document.getElementById('pointsdiv').style.display = 'block';
document.getElementById('stampdiv').style.display = 'none';
}
else if($type === 'stamp') {
$radios.filter('[value=stamp]').prop('checked', true);
document.getElementById('stampdiv').style.display = 'block';
document.getElementById('pointsdiv').style.display = 'none';
}
});
My HTML and PHP:
$type = $_SESSION['user']['type']; //Note: This is actually set at the very top of the page i.e. before the JS
<form autocomplete="off" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" role="form">
<input type="radio" id="selection" name="selection" value="points"></input><label>Points</label>
<input type="radio" id="selection" name="selection" value="stamp"></input><label>Stamps</label><br></br>
<div id="option">
<div id="pointsdiv">
//Points related information here
<input type="text" required="required"/>
</div>
<div id="stampdiv">
//Stamp related information here - below input is required so when pointsdiv is displayed, this entire div should not even load
<input type="text" required="required"/>
</div>
</div>
<button type="submit" class="button">Save</button>
</form>
Anyone have any ideas how I can load this page and post the form if I don't change the radio button - i.e. if it loads with "Points" checked and I click the Save button?
Input radio groups must have the same name but not the same id,
so you should change id="selection" for one of them.
If everything is in the same page and the page is in php,
then you have to wait for dom ready before setting input values.
There is a dynamic way without using javascript :
<input type="radio" <?=$type =='points'?='checked="checked"':''?> id="selection" name="selection" value="points">
The same thing you can do with the other radiobutton
and also with the divs pointsdiv and stampdivs
sorry about my limited coding skills and so on, but hopefully you can see what I am attempting. I want to scrap the form checkboxes and have 2 simple 'yes' 'no' hyperlinks, dependant on if image is hidden or shown. Will javascript do this? This is what I have so far, which was working but like I say, I just want 2 links instead of checkboxes.
if ($_POST['option']) {
if ($_POST['option'] == 'yes') {$hidden = 0;}
if ($_POST['option'] == 'no') {$hidden = 1;}
#mysql_query('UPDATE Image SET Hidden = ‘.$hidden.’ WHERE ID = '.$image->ID.'');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
<p>Show image?
<form method="post" action="?">
<input type="checkbox" name="option" value="yes">Yes
<input type="checkbox" name="option" value="no" >No
<input type="submit" name="submit" value="Go!" />
</form>
So then I can have HTML such as -
Show Image? Yes / No
(This image is shown) or (this image is not shown)
Any points in the right direction would be greatly appreciated, Many thanks!
Hi Guys, Sorry, I don’t think I explained myself properly.
All images have a default value of ‘Hidden = 0’ in the image database table, so they are all currently shown on the page. Here is the code -
// there is some SQL here that fetches all images
// here is the actual code that shows images:
foreach($ids as $id)
{
$tmp = new Image($id,true);
if (!$tmp->ID) continue;
<p>
<img src=”/myurl/’.$tmp->ID.’.jpg”>
</p>
}
What I want is, in that loop, underneath each image tag, is to have some HTML :
<p>Show Image? Yes / No </p>
I want the ‘yes’ and ‘no’ to be hyperlinks, which state will depend on the images ‘Hidden’ value.
So if the image is shown (all currently are), the word ‘Yes’ won’t be a clickable hyperlink, only ‘No’ will be.
If I then click ‘No’ I need it to post a query on click, to set Hidden = 1, to hide the image.
If the image is already hidden, then ‘Yes’ would be the only clickable link, which if clicked would post value Hidden = 0, so the image is shown.
I hope that makes sense. The other problem I have is the fact that there are multiple images, so the form or whatever system I use, needs to distinguish which image it is changing the Hidden value for.
In the code, the image’s unique id field is accessed like this: $tmp->ID
If you want hyperlinks just use something like
Yes
No
Also you will probably want to use single quotes ''s and not ‘'s for your query. Also I'd recommend using mysqli or PDO so you can use prepared statements instead of mysql_ functions which are prone to mysql injections.
Easiest way would be to use a hidden input field that will be submitted with the rest of your form and using javascript to change the value of that hidden field.
HTML:
<p>Show image?
<form method="post" action="?">
<input type="hidden" name="option" value="default" />
Yes
No
<input type="submit" name="submit" value="Go!" />
</form>
JS (requires JQuery):
$(".option").click(function (e) {
$("input[name=option]").val($(this).attr("data-value"));
});
Then when you submit the form $_POST should have the "option" value.
Try this
if(isset($_GET['cmd']))
{
if($_GET['cmd']=='yes')
{$hidden = 0;}
if($_GET['cmd']=='no')
{$hidden = 1;}
#mysql_query('UPDATE Image SET Hidden = '.$hidden.' WHERE ID = '.$image->ID.'');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<p>Show image? <br />
Yes <br /> <!--Replace page url according to yours -->
No
Just to reaffirm, the following form is my latest revision and works perfectly, updating the database and radio buttons on the page. However, it is still not the solution I want. I want hyperlinks only, as in the above examples posted by Boshi and Class, but for some reason my site won't accept those urls, the system churns me out to a different page and nothing works.
Here is the latest revision which works. Is there another solution? -
if ($_POST[''.$tmp->ID.'']) {
if ($_POST[''.$tmp->ID.''] == 'yes') {$hidden = 1;}
if ($_POST[''.$tmp->ID.''] == 'no') {$hidden = 0;}
#mysql_query('UPDATE Image SET Hidden = '.$hidden.' WHERE ID = '.$tmp->ID.' LIMIT 1');
header ('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
<p>Hide image?
<form method="post" action="?">
<input type="radio" name="'.$tmp->ID.'" value="yes" '.($tmp->Hidden ? 'checked' : '').'>Yes
<input type="radio" name="'.$tmp->ID.'" value="no" '.(!$tmp->Hidden ? 'checked' : '').'>No
<input type="submit" name="submit" value="Go!" />
</form>