Im creating a exam using php.
My problem is when the page is refresh the checked in the radio button dissappear.. i using ajax to save it in database everytime the radio button is click
<?php
session_start();
include './connect.php';
?>
<html>
<head>
</head>
<body>
<div id="online"></div>
<?php
$result = mysql_query("SELECT * FROM questions");
$count = mysql_num_rows($result);
while($rows = mysql_fetch_array($result))
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script>
function saveans(){
var aa = $('input:radio[name=a1]:checked').val();
alert(aa);
$.ajax({
type: "POST",
url: "ans.php",
data: "stdID=1&q=2&ans="+aa,
})
}
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#online").load("./tmr.php");
var refreshId = setInterval(function() {
//alert("aa");
$("#online").load('./tmr.php');
$.ajax({
type: "POST",
url: "./update.php",
data: "stdID=1"
})
}, 1000);
$.ajaxSetup({ cache: false });
});
</script>
<p><?php echo $rows["questions"]; ?></p>
<input type="radio" id="a<?php echo $rows['questionNum']; ?>" name="a<?php echo $rows['questionNum']; ?>" value="A" onClick="saveans(this);"/>A. <?php echo $rows['choi1']; ?><br/>
<input type="radio" id="a<?php echo $rows['questionNum']; ?>" name="a<?php echo $rows['questionNum']; ?>" value="B" onClick="saveans(this);"/>B. <?php echo $rows['choi2']; ?><br/>
<input type="radio" id="a<?php echo $rows['questionNum']; ?>" name="a<?php echo $rows['questionNum']; ?>" value="C" onClick="saveans(this);"/>C. <?php echo $rows['choi3']; ?><br/>
<input type="radio" id="a<?php echo $rows['questionNum']; ?>" name="a<?php echo $rows['questionNum']; ?>" value="D" onClick="saveans(this);"/>D. <?php echo $rows['choi4']; ?><br/>
<?php
}
?>
</body>
</html>
and the php code is
<?php
include './connect.php';$command = mysql_query("UPDATE ans_1 SET ans".$_POST['q']."='".$_POST['ans']."' WHERE std_id='".$_POST['stdID']."'") or die(mysql_error());
?>
the problem is i what to change the data: "stdID=1&q=2&ans="+aa.. the name of my radio button is a1,a2,a3 for multiple radio buttons.. i want to save it on my database depends the name Is it possible to insert database value in a ajax variable? and the std value is come from session
You define your function as :
function saveans(){
^---no arguments
But invoke it in your onclick handers as:
onClick="saveans(this);"
^^^^---passing in "this"
You want:
function saveans(obj) {
answer = obj.value;
... do ajax ...
}
There's no need to look up by ID (and a hard-coded id at that), since this
and obj
will already be the exact same DOM element you're trying to look up by ID anyways.