两个按钮用AJAX形成提交

时间:2017-11-10 16:30:59

标签: php ajax mysqli

嘿,我有一个带有两个提交按钮和一个简单文本输入的表单。我希望表单由ajax提交(我想出了如何做到这一点)。

形式:

<form method='post' action='likesystem.php' id='7'>
<input class='form-control' type='hidden' value='7' name='postid'>

<button type='submit' class='btn btn-success btn-sm' name='poslike' value='liking'>Like this</button>
<button type='submit' class='btn btn-danger btn-sm' name='poslike' value='disliking'>Dislike this</button>

脚本如下:

<script>
$('#7').on('submit', function(event) {
event.preventDefault();

$.ajax({
  url: 'likesystem.php',
  type: 'POST',
  data: $('#7').serialize(),

});
});
</script>

php页面:

<?php    

require_once 'config.php';

        $link = mysqli_connect($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);

        if(! $link ) {
           die('Could not connect: ' . mysql_error());
            echo "Connection Error";
        }

if($_SERVER["REQUEST_METHOD"] == "POST") {
$postid = $_POST['postid'];


switch($_POST['poslike']) {
    case 'liking':
        $sql = "UPDATE posts SET poslike = poslike + 1 WHERE id = $postid";

    case 'disliking':
        $sql = "UPDATE posts SET dislike = dislike + 1 WHERE id = $postid";

}

if (mysqli_query($link, $sql)) {
            echo "You did something";
        } else {
            echo "There was an error";
        }

mysqli_close($link);
}

我在这里做错了什么?我已经检查了多个网站,但那里的答案可能会有所帮助,这就是我现在在这里提问的原因。

1 个答案:

答案 0 :(得分:0)

将表单更改为:

<form method='post' action='likesystem.php' id='7'>
    <input class='form-control' type='hidden' value='7' name='postid' id='postid'>

    <button type='submit' class='btn btn-success btn-sm vote' name='poslike' value='liking'>Like this</button>
    <button type='submit' class='btn btn-danger btn-sm vote' name='poslike' value='disliking'>Dislike this</button>

</form>

并尝试使用以下脚本代码:

 <script>
    $('.vote').on('click', function(event) {
        event.preventDefault();
        var postid = $('#postid').val();
        var poslike = $(this).attr('value');
        $.ajax({
            url: 'likesystem.php',
            type: 'POST',
            data: 'postid=' + postid + '&poslike=' + poslike,
        });
    });
</script>