php - jQuery keyup 函数在尝试插入数据库时​​停止工作

标签 php jquery mysql database mysqli

这是一个奇怪的问题,我不确定如何处理它。

目前我正在尝试让用户输入一种成分 - 当您键入成分列表时会出现成分列表,旁边有按钮可以添加它们,这应该将它们插入到 SQL 数据库中。

当我取消注释时列表人口停止运行

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

在添加按钮的.click函数中。 这很奇怪,因为它就像 .keyup 函数刚刚停止工作。

    <html>
    <head>
    <title>Cocktails</title>
    <script src="http://assets.absolutdrinks.com/api/addb-0.5.2.min.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>


    <body>

        <form>
          <input type="text" name="ingredientinput" id="ingredientinput"><br>
        </form> 
        <div id="ingredientlist">

        </div>

        <script>

            $(document).ready(function(){

                //ajax call to query cokctail DB 
                //handleData is callback function that handles result
                function get_ingredients(query,handleData){
                    var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
                    var rooturl = "http://addb.absolutdrinks.com/";
                    $.ajax({
                        type: "GET",
                        url: rooturl + "/quickSearch/ingredients/" + query + "/",  
                        dataType: 'jsonp',
                        data: {apiKey:apikey},
                        success: function(data) {

                                handleData(data);
                            },
                        error: function(){
                            //error
                        }
                    });
                }





                //when text is entered - quicksearch the database
                $("#ingredientinput").keyup(function(){
                    query = $(this).val();                  //value of textbox
                    divlist = "";                           //list of ingredients
                    objectlist = {};
                    if (query.length > 0){
                        //set loading image on keypress
                        $("#ingredientlist").html("<img src='images/spinner.gif' alt='loading' height='24' width='24'>");

                        //pass query to ajax call and handle result
                        get_ingredients(query,function(data){
                            console.log(data);

                            //build list of ingredients
                            $.each(data["result"], function(key, value){

                                divlist += "<div id='" + value["id"] + "'>" + value["name"] + "<button class='addbutton' type='button' id = '"+value["id"]+"'>+</button></div>";                            
                                objectlist[value["id"]] = value;


                                //clicking button dumps object to file?
                            });

                            $("#ingredientlist").html(divlist);         //populate div ingredientlist with results
                            divlist = "";                               //clear html builder
                        });
                        console.log("input query:" + query);

                    }
                    else{
                        $("#ingredientlist").html("");                  //if no input clear list
                    }
                });

                $("#ingredientlist").on('click','button.addbutton',function(){
                    $("#ingredientlist").on('click','button.addbutton',function(){

                    current = objectlist[this.id];
                    sqlquery = current["description"] + "," + current["id"] + "," + current["isAlcoholid"] + "," + current["isBaseSpirit"] + "," + current["isCarbonated"] + "," + current["isJuice"] + "," + current["languageBranch"] + "," + current["name"] + "," + current["type"];
                    console.log(sqlquery);
                    <?php



                        $servername = "localhost";
                        $username = "root";
                        $password = "**";
                        $dbname = "ingredients";


                        $conn = mysqli_connect($servername, $username, $password, $dbname);

                        $sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
                        VALUES ('test','test','test','test','test','test','test','test','test',)";

                        if ($conn->query($sql) === TRUE) {
                            echo "New record created successfully";
                        } else {
                            echo "Error: " . $sql . "<br>" . $conn->error;
                        }

                        mysqli_close($conn);

                        ?>





                });
                });

            });

        </script>

    </body>
</html>

最佳答案

您不能像现在这样从 javascript 中嵌入一个保存查询。这是一个需要发生并返回结果的服务器端函数(几乎就像您正在使用 get_ingredients 函数一样。)

我的建议是创建一个 save_ingredients 函数,它通过 ajax 将信息(在本例中是要保存的成分)传递给服务器。

saveingredients.php 中:

<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";

$conn = new mysqli($servername, $username, $password, $dbname);

$description = filter_input(INPUT_GET, 'description', $_GET['description'], FILTER_SANITIZE_SPECIAL_CHARS);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$isAlcoholic = filter_input(INPUT_GET, 'isAlcoholic', FILTER_VALIDATE_BOOLEAN);
$isBaseSpirit = filter_input(INPUT_GET, 'isBaseSpirit', FILTER_VALIDATE_BOOLEAN);
$isCarbonated = filter_input(INPUT_GET, 'isCarbonated', FILTER_VALIDATE_BOOLEAN);
$isJuice = filter_input(INPUT_GET, 'isJuice', FILTER_VALIDATE_BOOLEAN);
$languageBranch = filter_input(INPUT_GET, 'languageBranch', FILTER_SANITIZE_SPECIAL_CHARS);
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$type = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_SPECIAL_CHARS);

$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

if ( $stmt = $conn->prepare($sql) )
{
    $stmt->bind_param('sdsssssss', $description, $id, $isAlcoholic, $isBaseSpirit, $isJuice, $languageBranch, $name, $type);

    if ($stmt->execute($sql) === TRUE) {
        echo json_encode('error' => false);
    } else {
        echo json_encode('error' => 'MySQL Error: ' . $conn->error);
    }
}


$conn->close($conn);

?>

AJAX 函数示例:

function saveingredients(current) {
    $.ajax({
        url: 'saveingredients.php',
        data: {
            description: current["description"],
            id: current["id"],
            isAlcoholid: current["isAlcoholid"],
            isBaseSpirit: current["isBaseSpirit"],
            isCarbonated: current["isCarbonated"],
            isJuice: current["isJuice"],
            languageBranch: current["languageBranch"],
            name: current["name"],
            type: current["type"]
        },
        success: function(res) {
            if ( res.error )
            {
                console.log(res.error);
            }
            else
            {
                //Do something here because it inserted correctly.
            }
        },
        failure: function(err) {
            console.log(err);
        }
    });
}

关于php - jQuery keyup 函数在尝试插入数据库时​​停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693242/

相关文章:

php - 具有多个选项过滤器 mysql 和 php 的产品

php - 流交互 As3 -> PHP -> Mysql -> C++

mysql - 测试中的命令导致测试无法完全退出

php - 使用php向数据库中插入数据

javascript - Web 中的安全身份验证

jquery - 无法在 jquery UI 对话框中设置输入字段的值

jquery - 扩展 jquery $(this)

javascript - 如何使用 Javascript 或 jQuery 将一个对象的属性复制到另一个对象而不添加属性?

php - 如何在数据库中按ID(主键)显示记录以在codeigniter中自动或动态查看?

php - 回显标签(文本)在页面上不可见