通过ajax将变量从html表单发送到php函数的正确方法


Correct method of sending a variable from a html form to a php function via ajax

我正在为多次上传编写一个投票系统;每个上传的图像都在foreach语句中,每个语句都附有一个表单,有三个按钮可以向上、向下或无投票,每个按钮都与我的mysql数据库中的INT相关联。

我通过将表单数据直接提交给‘UPDATE’数据库的PHP函数来实现它。为了避免页面刷新,我附加了ajax。我让ajax发送PHP函数更新数据库中正确的"image"行和INT所需的两个变量。

问题:ajax函数有效,但PHP函数似乎没有更新。

可疑问题:我很确定这是我在ajax中定义要传递的变量的方式,我试图获取它正在处理的"图像"的ID,但我不知道如何将这些数据转换为PHP函数,使其正确更新。

以下是表单、javascript和php:

// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each 
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this 
// hidden input, to send unique ID
<input type="hidden" name ="input_id" 
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answerswer_L" id="<?php echo $row['id']; ?>" 
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
        type: 'POST',
        url: 'feed.php', //name of this file
        data:input_id,post_answer1,
        cache: false,
        success: function(result)
                {
                alert ('It worked congrats');
                }
    });
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
                $current_id = $_POST['input_id'];
                $vote_1 = "UPDATE decision_post set " . 
                   "post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
                $run_vote1 = mysqli_query($conn2, $vote_1); 
                if($run_vote1){ echo 'Success'; }
}
?>

这里有一个简单的答案,只需序列化所有表单数据!

$('form').submit(function(){
    $.post('feed.php', $(this).serialize(), function(data){
        console.log(data);
    }, 'json');
    return false;
});
var post_answer1 = $("input[name='post_answer1']").val();