获取单选按钮值并通过ajax发送到php
问题描述:
我在我的网站上有一个民意调查,它显示每个答案旁边的单选按钮。当用户选择一个选项并提交时,即时通过ajax运行一个php脚本,将值或选中的单选按钮插入到表中。获取单选按钮值并通过ajax发送到php
我的Ajax正在运行,但当前每行插入一行0,所以它没有从单选按钮中获取值。任何帮助,将不胜感激。
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:(缩短版)
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')";
提前感谢!
答
$("#submit_vote").click(function(e){
$.ajax({
type: "POST",
url: "ajax_submit_vote.php",
data: $('#poll_form').serialize(),
success: function(response) {}
});
});
你应该再有POST变量“poll_option”在你的PHP脚本访问。
+0
谢谢StuR完美地工作:) – 2013-04-04 15:10:06
答
$optionID = "="+optionID;
我不太明白你正试图在这里做o.O,在JavaScript中使用$
您的变量,你没有定义。
data: { optionID : option}
像这样使用它应该工作。你会找回它像这样在PHP:
$option_value=$_POST['optionID'];
答
var option = $('input[type="radio"]:checked').val();
$.ajax({
type: "POST",
url: "ajax_submit_vote.php",
data: { poll_option : option }
});
在PHP你正在阅读$_POST['poll_option']
因此,你必须使用poll_option
在你的数据对象的关键。另外,当您尝试使用时,该值存储在option
而不是$optionID
中。
的$
是在Javascript中的变量名有效的字符,它不会做什么特别的事情本身,而是一些程序员前缀任何与$
一个jQuery对象,这样他们就可以翻阅代码,并很容易地看到哪些变量已经有jQuery包装。
例如:
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.
'数据:{ “optionID”:$ optionID}'应该是'数据:{optionID:$ optionID}' – tiagojpdias 2013-04-04 14:47:00
您是否获得在选项变量的正确值开始用?如果不尝试 '$('input [type =“radio”] ['name = poll_option']:checked')。val();' 注意在类型之后添加了['name-poll_option'] =“无线电” – Keeleon 2013-04-04 14:48:37