I have a poll on my website which displays radio buttons next to each answer. When the user selects an option and submits, im running a a php script via ajax to insert the value or the selected radio button into a table.
My Ajax is running but is currently inserting a 0 row each row, so it's not picking up the value from the radio button. Any help would be appreciated.
HTML:
<form id="poll_form" method="post" accept-charset="utf-8">
<input type="radio" name="poll_option" value="1" id="poll_option" /><label for='1'> Arts</label><br />
<input type="radio" name="poll_option" value="2" id="poll_option" /><label for='2'> Film</label><br />
<input type="radio" name="poll_option" value="3" id="poll_option" /><label for='3'> Games</label><br />
<input type="radio" name="poll_option" value="4" id="poll_option" /><label for='4'> Music</label><br />
<input type="radio" name="poll_option" value="5" id="poll_option" /><label for='5'> Sports</label><br />
<input type="radio" name="poll_option" value="6" id="poll_option" /><label for='6'> Television</label><br />
<input type="submit" value="Vote →" id="submit_vote" class="poll_btn"/>
</form>
AJAX:
$("#submit_vote").click(function(e)
{
var option=$('input[type="radio"]:checked').val();
$optionID = "="+optionID;
$.ajax({
type: "POST",
url: "ajax_submit_vote.php",
data: {"optionID" : $optionID}
});
});
PHP: (shortened version)
if($_SERVER['REQUEST_METHOD'] == "POST"){
//Get value from posted form
$option = $_POST['poll_option'];
//Insert into db
$insert_vote = "INSERT into poll (userip,categoryid) VALUES ('$ip','$option')";
Thanks in advance!
$("#submit_vote").click(function(e){
$.ajax( {
type: "POST",
url: "ajax_submit_vote.php",
data: $('#poll_form').serialize(),
success: function( response ) {}
});
});
You should then have the POST variable "poll_option" accessible in your PHP script.
var option = $('input[type="radio"]:checked').val();
$.ajax({
type: "POST",
url: "ajax_submit_vote.php",
data: { poll_option : option }
});
In the PHP you are reading $_POST['poll_option']
therefore you must use poll_option
as the key in your data object. Also, the value is stored in option
not $optionID
as you were trying to use.
The $
is a valid character in variable names in Javascript, it doesn't do anything special itself but some coders prefix anything that is a jQuery object with $
so they can glance through code and easily see what variables already have the jQuery wrapper.
For example:
var $option = $('input[type="radio"]:checked'); // $option is the jQuery wrapped HTML element
var myValue = $option.val(); // we know $option already has the jQuery wrapper so no need to use the $(..) syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With