尝试查找单击了哪个按钮,并将结果推送到DB

时间:2014-10-12 16:28:22

标签: javascript php jquery

所以这是我的JS脚本,在我的头标记中:

<script>
            $(document).ready(function() {
                $(".chooseMood").click(function(){
                    var id = $(this).attr('id');


                    $.ajax({

                        url: 'demosys.php',
                        data: {mood: $( '#id' ).val(),
                        success: function(data){
                            $('#mood').html(data);   
                        }
                    });
                });

            }); 
            </script>

包含按钮的HTML:

<div class = "chooseMood">
                    <button type="submit" name="happy" id = "happy" value="happy_btn_was_clicked">
                        <img src="Images/happy.png" />
                    </button>
                    <button type="submit" name="sad" id="sad" value="sad_btn_was_clicked">
                        <img src="Images/sad.jpg" />
                    </button>
                    <script>
                     $('#happy').click(function() {
                         $("#sad").hide();
                     });

                    $('#sad').click(function() {
                         $("#happy").hide();
                     });                         
                    </script>


                </div>

php文件:

<?php
function submitMood($mood){

  $db_connection = new mysqli(/////);
  if(mysqli_connect_errno()){
    echo "Connection Error!";
    return;
  }


  $recentMood = mysqli_query($db_connection, "SELECT * FROM `DemoUser` ORDER BY date DESC LIMIT 1'");

  $today = date('Y-m-d');



  if($recentMood['date'] != $today){
     mysqli_query($db_connection, "INSERT INTO DemoUser (Mood, date) VALUES('$mood' , NOW())");
     echo "Mood recorded!";
  }

  else{


  echo "Mood already recorded.";
  }
}
submitMood($_GET['mood']);
?>

我试图找出点击了哪个按钮。每个按钮都与一个心情相关联,我想在点击后将该心情插入数据库。现在,我的情绪没有被添加到数据库中。

2 个答案:

答案 0 :(得分:0)

我认为你的代码工作正常,但那里有一点问题。将您的代码更改为:

data: { mood: $('#' + id).val() },

你应该连续&#39; <&#39; + id 然后读取它的值。你的选择器也是错误的:

$(".chooseMood button").click(...

答案 1 :(得分:0)

您不需要ID,只需使用this获取按钮的值

 $(".chooseMood button").click(function (e) {
     e.preventDefault(); /* prevent form submit*/
     var mood = $(this).attr('value');
     $.ajax({
         url: 'demosys.php',
         data: {
             mood: mood,
             success: function (data) {
                 $('#mood').html(data);
             }
         });
     });
});