0

ボタンのクリック数を数えています。PHPですべてが機能しました。ajax を追加すると、ボタンを 1 回クリックするとページがクラッシュします。私は何を間違えましたか?HTML、クラス、および ajax コードを挿入しました。

<script type="text/javascript">
$(document).ready(function(){
    $("#btn_like").click(function()
    {
        var counter;
        counter+=1;

        var counts={btn_like:like};

        $.ajax({
              type: "POST",
              url: "ajax/count_likes.php",
              data: counts
            }).done(function( msg ) {
              alert( "Data Saved: " + msg );

            });
    });
    });
</script>
</head>
<body>

    <form action="" method="post">
    <div id="like">
            <img id="aap" name="aap" src="images/aap.jpg" />
            <input type="submit" name="btn_like" id="btn_like" value="I like"/>  
            <?php if (isset($likes)) {$numLikes=$likes->fetch_assoc();
 echo "<span>"; echo $numLikes['likes_num']; echo "</span>"; }?>

        </div>
    </form>

これがクラスです

<?php
    class User
    {
    private $m_sLike;

    public function __set($p_sProperty, $p_vValue)
    {
        switch($p_sProperty)
        {
            case "Like";
                $this->m_sLike = $p_vValue;
        }      
    }

    public function __get($p_sProperty)
    {
        $vResult = null;
        switch($p_sProperty)
        {
        case "Like";
            $vResult = $this->m_sLike;
            break;
        }
        return $vResult;
    }
    public function getLikes()
    {
        include("Connection.php");
        $sSql = "select * from tbllikes";   
        $result = $link->query($sSql);
        return($result);
    }
    public function updateLikes()
    {
        include("Connection.php");
        $sql = "UPDATE tbllikes SET likes_num=likes_num+1 WHERE likes_id=1";
        $vResult = $link->query($sql);
    }
    }
    ?>

AJAX - ファイル

<?php
    include ('../classes/User.class.php');

    if(isset($_POST['btn_like']))
        {
            $val=new User();
            $val->Likes=$_POST['btn_like'];
            $val->updateLikes();

            //echo $val;
            $likes=$val->getLikes();
        }
    header('Content-type: application/json');
    echo json_encode($likes);
 ?>
4

1 に答える 1

3

Your are not preventing the default submit button behaviour, so it will do the normal form submit.

You can use preventDefault to do that

$("#btn_like").click(function(e)
{
  e.preventDefault();    
   //Your rest of the code

});

http://api.jquery.com/event.preventDefault/

Use firebug and see whether you are running in to any other script errors.

于 2012-04-25T13:20:22.943 に答える