我有一個工作表單,將星級評分(1到5)保存到mysql數據庫。我現在試圖使這個表單提交與Ajax,但我只有得到值「5」保存到我的數據庫(所有其他變量保存很好)。誰能告訴我什麼是錯的?非常感謝。爲什麼我的Ajax表單不提交正確的值?
表單
<form>
<input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
<label class="star star-5" for="star-5"></label>
<input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
<label class="star star-4" for="star-4"></label>
<input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
<label class="star star-3" for="star-3"></label>
<input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
<label class="star star-2" for="star-2"></label>
<input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
<label class="star star-1" for="star-1"></label>
<input type="hidden" name="username" value="<?php echo $username;?>">
<input type="hidden" name="film_id" value="<?php echo $film_id;?>">
<button type="submit" id="FormSubmitRate" class="btn btn-primary btn-xs pull-right">Rate!</button>
</form>
jQuery的
//Add Rating
$(document).ready(function(){
$("#FormSubmitRate").click(function (e) {
e.preventDefault();
var username=$("#username").val();
var film_id=$("#film_id").val();
var star=$("[name=star]").val();
$.post('ajax_addrating.php', {username: username, film_id: film_id, star: star},
function(data){
$("#message").html(data);
$("#message").hide();
$("div.success").fadeIn(500); //Fade in the data given by the insert.php file
$("div.success").fadeOut(2500); //Fade in the data given by the insert.php file
$("div.success").html();
});
return false;
});
});
</script>
ajax_addrating.php
<?php
//include db configuration file
include_once("config.php");
//Configure and Connect to the Database
if (!$mysqli) {
die('Could not connect: ' . mysqli_error());
}
$username=$_POST['username'];
$film_id=$_POST['film_id'];
$rating=$_POST['star'];
//Insert Data into mysql
$stmt = $mysqli->prepare('INSERT user_reviews SET rating = ?, film_id=?, username=?');
$stmt->bind_param('sss', $rating, $film_id, $username);
$stmt->execute();
if ($stmt->errno) {
echo "There was an error " . $stmt->error;
} else{
echo " Success!";
}
?>
可能重複的:http://stackoverflow.com/questions/986120/in- jquery-how-do-i-select-an-element-by-its-name-attribute –