Changing yes/no value in database, on click of hyperlink - javascript

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>

Related

Chrome Auto-checked radio button, hidden div with "required" blocking POST

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

Radio buttons to new page

Hey guys sorry to ask this, but I am stumped, I want the code to go to the pages with the action when the radio button is clicked, like stupid radio button to stupid.php here's the form
<form name = "quoted" method="get">
<input id = "poster" type="text" name="poster" required="required" placeholder = "Credited Individual.">
<br>
<textarea class = "actual_quote" name = "actual_quote" required="required" placeholder = "Write the question here!"></textarea>
<br><br><br>
<div class = "checkboxes" required="required">
<h3 style = "margin-top:-20px;">Please select one catagory that the quote falls into.</h3>
<label for="x"><input type="radio" name="x" value="stupid" id = "x" checked="checked" action = "stupid.php" /><span>stupid</span></label>
<br>
<label for="x"><input type="radio" name="x" value="stupider" id = "x" action = "stupider.php" /><span>stupider</span></label>
<br>
<label for="x"><input type="radio" name="x" value="stupidest" id = "x" action = "stupidest.php" /><span>stupidest</span></label>
</div>
<input id = "submit1" type="submit"><br>
</form>
and here's the php on each of the pages, stupid, stupider, and stupidest, the php error is saying that actual-quote and poster are not identified indexes, help?
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Question.</h2>
<div class="checkboxes"><?= !empty($_GET['x']) ? $_GET['x'] : '' ?>
</div>
</div>
<div class="top-submit"><?php echo '“' . (!empty($_GET['actual_quote']) ? $_GET['actual_quote'] : '') . '”'; $actual_quote = $_GET['actual_quote'];?>
</div>
<div class="poster"><?php echo "-" . (!empty($_GET['poster']) ? $_GET['poster'] :''); $poster = $_GET['poster'];?>
<div class = "like">
Like
<p id = "like" style = "color:green;">0</p>
</div>
<div class = "dislike">
Dislike
<p id = "dis" style = "color:red;">0</p>
</div>
</div>
<?php
"INSERT INTO submissions(top-submit, poster)
VALUES ($actual_quote, $poster)";
?>
</div>
</div>
I am sorry to ask, but I have been trying for an hour and I have run out of ideas. Any suggestions is GREATLY welcomed.
Just to clarify, I want each of the radio buttons, when selected, to a new page once they click the submit button, i want to have them check one radio option, and then click submit and be directed to the page.
v
DEMO
<label for="x"><input type="radio" name="x" value="stupid" id = "x" checked="checked" action = "stupid.php" /> <span>stupid</span></label><br>
Based on your radio buttons,
$("input[type=radio]").click(function() {
window.location.href = $(this).attr("action");
});
So when the user clicks on any one of the radio buttons, the click handler will take him to the respective page mentioned in the action attribute.
In case if you want to redirect only if the radio button is checked and not when its unchecked, use if($(this).is(":checked")) to check the condition
I fail to understand why are you not using anchors for redirecting instead of messing up with inputs. If you use anchors, then you don't need any custom attributes of action on inputs.
Moreover if you have a form then why not simply use it's action attribute for the purpose. And in the backend you can handle the redirect easily instead of relying on the javascript redirect.
Still, if you want to use inputs for navigation and redirecting and since you didn't mentioned anything about jQuery, I assume you need pure Javascript solution. You can use inline javascript in the inputs like:
<label><input type="radio" action="http://www.google.com" onclick="window.location.href=this.action;" />Google</label>
If you need a jQuery solution, refer to the solution provided above by mohamedrias.
Are you trying to post values to different php files based on the selection of radio button. If yes, I think you can achieve the same using jquery.
$("input[type='radio']").click(function(){
$("form").attr('action',$(this).attr('action'));
});
The above code will add click event handlers to all the radio buttons. When the user clicks the radio button, the action property from the radio button will be set to the form. When the form is submitted, it will be calling the php file set in the action property of the currently selected radio button

How to change div id name based on form value?

I have a couple forms on a page with a single button and a hidden input field with a value already pre-set:
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
Once they hit the Go button on either form, it will redirect to the product.html page where a specific div loads based on the value above.
<div id="ID CHANGE TO OCCUR HERE to either be RSS or RSS2"></div>
My question is, how do I get that id to change on that div?
Thanks
PS: PHP is not enabled on the company servers...so yeah..yeah...
If I understand you correctly, when program control transfers over to product.html, you wish to discover which form value has come across (i.e. which form did the user click).
I cannot think how you would do this solely with HTML. This is a job for a server-side language like PHP or ASP .Net.
It's pretty simple in PHP. Note that you can take all your existing HTML files and simply rename them to .php (eg. product.php) and they will still work the same.
Just put this at the top of the file -- in fact, this is the complete file (just copy/paste to your server to test):
product.php
<?php
/* Below not required, but un-comment to see useful info:
echo '<pre>';
print_r($_REQUEST);
echo '<pre>';
*/
if (isset($_REQUEST['RSS'])) {
echo 'User clicked the RSS form';
} else if (isset($_REQUEST['RSS2'])) {
echo 'Sent here by the RSS2 form';
}
Since the name of the processing file has changed, remember to change the action= line in each of your forms before trying this:
<form action="product.php" method="get">
Explanation:
When a form is submitted, the form elements (input fields, radio buttons, checkboxes) are turned into variables and sent to the processing document (the target document specified in the action= attribute of the form tag).
For each element, the variable name is the name= attribute for that element, and the variable value is either the value= attribute, or, in the case of an input field for example, whatever the user typed into the field before pressing submit.
The is very little difference to the programming/functionality between sending the form as method="Get" or method="POST", but the post method is more secure and can transfer more information, so most of us use that.
Finally, on the other end, there are three ways to get the variable values (PHP Example):
$newvar = $_GET['varname']; //if method="GET" was used
$newvar = $_POST['varname']; //if method="post" was used
$newvar = $_REQUEST['varname']; //works for both
If you need more assistance with PHP, view some of the Alex Garret's free ten-minute videos on the New Boston or on his own site.
Re-reading your question, I put together the completed example. In your target page, you have two DIVs and you wish to display one or the other depending on what form the user clicked.
Here is a working example of the solution. Copy/Paste into two files called:
test.php -- this file can be renamed whatever you want
product.php -- if change this name, must also change name in both action= attributes of forms
test.php
<form action="product.php" method="get"> <!-- product.html -->
<fieldset>
<input type="hidden" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.php" method="get">
<fieldset>
<input type="hidden" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
product.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var whichone = $('#xfer').val();
//alert( whichone );
$('#' + whichone).show();
});
</script>
</head>
<body>
<input type="hidden" id="xfer" value="<?php echo ( isset($_REQUEST['RSS']) ? 'RSS' : 'RSS2' ) ; ?>">
<div id="RSS" style="display:none;">
<h1>RSS DIV</h1>
Here is some information regarding the RSS div.
</div><!-- #RSS -->
<div id="RSS2" style="display:none;">
<h1>RSS2 DIV</h1>
<i>Here is some <strong>different </strong>information regarding the RSS2 div.</i>
</div><!-- #RSS -->
</body>
</html>
You can test your request with javascript:
if(location.href.indexOf("RSS=RSS") > 0) {
var element = document.getElementById('RSS')
element.id = "RSS2";
element.name = "RSS2";
element.value = "RSS2";
}
this is just an indexOf check, u could also parse the whole query string and associate the key/value pairs into an array. See How can I get query string values in JavaScript?

Getting checked value with ajax submit

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.

HTML + Javascript form submission question

I have authored a html + javascript form which displays a set of images along with a submit button. The user can select the images he or she is interested in and when the user clicks the image, I change the image border to indicate image selection.
And when the user clicks on the submit button, I would like my server side script to receive the image uris associated with the selected images for further processing.
I am a JS newbie. I would like to know how best to do this. Will I need a global javascript array which gets populated with the selected image URIs? And this array can then be submitted as part of HTTP POST?
Any tips/pointers will be helpful.
If I were you, I’d make sure it works without JavaScript too. E.g.
<form action="" method="POST">
<label for="image_1">
<img src="image_1_uri" alt="Image 1" />
<input type="checkbox" name="images" id="image_1" value="image_1_uri" />
</label>
<label for="image_2">
<img src="image_2_uri" alt="Image 2" />
<input type="checkbox" name="images" id="image_2" value="image_2_uri" />
</label>
<input type="submit" />
</form>
Then adapt your border-adding JavaScript to work when the label is clicked on, rather than the image.
Hide the checkboxes via CSS if you’re not keen on them being there. (You’ll need to add a class to the checkboxes to do this in older versions of Internet Explorer.)
Try this:
//...let's suppose this is the image you change the border of on click..
<img src="whatever" onclick="createHidden(this);" />
<script type="text/javascript">
function createHidden(field)
{
var hdn = document.createElement("input");
hdn.setAttribute('type', 'hidden');
hdn.setAttribute('name', 'hdn[]');
hdn.setAttribute('value', field.src); // populate images src now
var frm = document.getElementsByTagName("form")[0];
frm.appendChild(hdn);
}
</script>
Now you can access the images' paths in the hdn array in your server-side script.

Categories