PHP在jQuery Post之后无法正常工作

时间:2016-06-24 03:16:16

标签: php jquery ajax

我试图建立一个投票系统,用户可以根据需要多次投票,并且每次点击投票按钮时都会更新投票#(无需刷新)。

我的问题是,当我尝试进行$ .post调用时(我已经尝试过其他方法),变量没有设置(我认为),所以没有被查询到我的数据库,每当我点击。

以下是代码:

list.php的

<?php  

    //Require login file -- Fatal error if not found
    require_once('login.php');

    //Connect w/ MySQL database  [login variables]
    $con = new mysqli($hn, $un, $pw, $db);

    //If connection error -> kill application and display error
    if ($con->connect_error) die('Connect Error (' . $con->connect_error . ') '. $con->connect_error);

    if (isset($_POST)) {

    }

    //heading
    echo <<<_END
        <!DOCTYPE html>
        <html>
        <head>
            <title>Testing</title>
            <!--Page Style-->
            <link type="text/css" rel="stylesheet" href="Style.css">

            <!--jQuery-->
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

            <!--RateYo | http://prrashi.github.io/rateYo/-->
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.css">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.js"></script>

            <!--Font Awesome-->
            <script src="https://use.fontawesome.com/d785d4b203.js"></script>

        </head>
        <body>
_END;

    //retrieve databse items
    $query = "SELECT * FROM items ORDER BY difficulty DESC";
    $result = $con->query($query);
    if (!$result) die($con->error);

    $rows = $result->num_rows;


    //display items
    for ($j = 0; $j < $rows; ++$j) {
        $result->data_seek($j);
        $row = $result->fetch_array(MYSQLI_ASSOC);

        //random color 
        $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
        $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];

        echo '<div class="listitem" data-id="'.$row['id'].'" data-votes="'.$row['votes'].'"style="background-color:'.$color.' "><div class="bcontain"><img class="badge" src="img/badge1.png" /></div><div class="goal">'.$row['goal'].'</div>';
        echo '<div class="vote"><span id="vnumb">'.$row['votes'].'</span> votes <i class="fa fa-sort-asc fa-3x" id="voteup"></i><span id="uptext">up</span></div>';
        echo '<div class="diff">Difficulty: '.$row['difficulty'].'</div></div> <br><br>';

    }

    echo <<<_END
        <script>
            $('.vote i').click(function(){

                var self = $(this); // cache 
                var parent = self.parent().parent(); // grab grand parent .item
                var id = parent.data('id'); // grab post id from data-postid
                var votes = parent.data('votes'); // grab score form data-score

                parent.data('votes', ++votes);

                //change html
                parent.find('#vnumb').html(votes);

                //send info to database
                $.post("ajaxvote.php", {postid : id}, function() {
                    alert("success");
                }); 
            })
        </script>
_END;

    //closing tags
    echo <<<_END
        </body>
        </html>
_END;

    //close connection
    $result->close();
    $con->close();

    function get_post($conn, $var) {
        return $conn->real_escape_string($_POST[$var]);
    }

?>

ajaxvote.php

 <?php
require_once('login.php');


  //Connect w/ MySQL database  [login variables]
  $con = new mysqli($hn, $un, $pw, $db);

  //If connection error -> kill application and display error
  if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);



  if (isset($_POST['postid'])) {
    $postId = $con->real_escape_string($_POST['postid']);

    echo '<script>alert("hello");</script>';

    # query into db table to know current voting score 
    $query = "SELECT votes FROM items WHERE id = '$postId' LIMIT 1";
    $result = $con->query($query);
    if(!$result) echo "INSERT failed: $query<br>" . $con->error . "<br><br>";

    # increase or dicrease voting score
    if ($con->fetch_array($result)) {
      $data = $con->fetch_array($result);
      $vote = ++$data['votes'];

      # update new voting score
      $con->query("UPDATE items SET votes = '$vote' WHERE id = '$postId' ");

    }
  }


$con->close();
?>

2 个答案:

答案 0 :(得分:1)

我认为问题在于你正在调用方法fetch_array两次并且结果是一行,每次后续调用fetch_array将返回下一行,摆脱条件中的fetch_array()并尝试检查结果数

# increase or dicrease voting score
if ($result->num_rows) {
  $data = $con->fetch_array($result);
  $vote = ++$data['votes'];

  # update new voting score
  $con->query("UPDATE items SET votes = '$vote' WHERE id = '$postId' ");

}

我希望这会有所帮助。

答案 1 :(得分:1)

好吧,所以我想出了问题。

if ($con->fetch_array($result)) {
  $data = $con->fetch_array($result);

应该是

if ($result->num_rows) {
  $data = $result->fetch_array(MYSQLI_ASSOC);

部分归功于@juliusbin编辑if参数

另一个问题是1.我没有在查询上调用fetch_array方法我在连接本身上调用了它2.我将结果传递给fetch数组而不是告诉它我想要什么类型的数组。

这就是孩子们,这就是为什么你不盲目跟随在线编码教程。