在侦听器中不调用AJAX函数

时间:2015-11-03 12:29:09

标签: javascript php jquery ajax

函数validate()不会在侦听器中调用,否则会导致错误。数据未添加到DB。 index.php文件: 函数validate()不会在侦听器中调用,否则会导致错误。数据未添加到DB。的index.php:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src = "jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){



            $("#add_button").click(function(){

                validate();

            });

        });

        function validate(){

            $.post("ajax_controller.php",

                {

                    act:"add",
                    subject:$("#subject").val(),
                    description:$("#description").val(),
                    price:$("#price").val(),
                    semester:$("#semester").val()

                }

            );

        }

    </script>
</head>
<body>
    <form action="add.php" method="post" id = "login_form">
        <input type="hidden" value="add" name = "act">
        <input type="text" name = "subject" id = "subject">
        <input type="text" name = "description" id = "description">
            <input type="text" name = "price" id = "price">
        <input type="text" name = "semester" id = "semester">

        <input type="button" id = "add_button" value = "add">

    </form>
</body>

和ajax_controller.php:

<?php
    echo "asd";
    if(isset($_POST['act'])){
        if($_POST['act']=='add'){

            $subject= $_POST['subject'];
            $description = $_POST['description'];
            $price = $_POST['price'];
            $semester = $_POST['semester'];

            $connection = new mysqli("localhost","root","","subjects");

            $query = $connection->query("insert into subjects(id, name, desctiption, price, semester) values(NULL, \"".$subject."\", \"".$description."\",  ".$price.", ".$semester." )");



        }
    }
?>

添加了jquery库。谢谢。

1 个答案:

答案 0 :(得分:0)

更改ajax_controller.php中的编码

       <?php
          if(isset($_POST['act'])){
              if($_POST['act']=='add'){

                 $subject= $_POST['subject'];
                 $description = $_POST['description'];
                 $price = $_POST['price'];
                 $semester = $_POST['semester'];

                 $connection = mysqli("localhost","root","","subjects");

                 $query = mysqli_query($connection,"insert into subjects(id, name, desctiption, price, semester) values(NULL, \"".$subject."\", \"".$description."\",  ".$price.", ".$semester." )");
              }
           }
       ?>

现在数据已添加到db