【问题标题】:jQuery keyup function stops working when trying to insert into a databasejQuery keyup 函数在尝试插入数据库时​​停止工作
【发布时间】:2015-08-21 23:32:22
【问题描述】:

这是一个奇怪的问题,我不知道如何解决。

目前,我正试图让用户输入一种成分 - 当您键入时,会出现一个成分列表,旁边带有添加它们的按钮,这些按钮应该将它们插入 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>

【问题讨论】:

  • 你不应该发布 api 密钥
  • @A.Wolff 这还不错,因为它是一个 javascript 端 API,任何查看其网站源代码的人都可以公开使用。
  • @FrankerZ 是的,你是对的

标签: php jquery mysql database mysqli


【解决方案1】:

您不能像现在这样在 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);
        }
    });
}

【讨论】:

  • 所以在 onclick 中有一个save_ingredients(sqlquery) 然后在该函数中使用 ajax 将对象传递给 php 文件并将其添加到数据库?
  • @Supertod,我认为你需要回去阅读 PHP 和 Javascript 101。PHP 是一种服务器端脚本语言,它处理请求并返回结果。 Javascript 是一种从客户端计算机运行的客户端语言。两者之间的任何交互都需要通过发送到服务器的适当请求(即 AJAX 或提交表单)来处理。您不能只在 javascript 中间转储 PHP,因为此时,您已经回显了一大串 javascript(由浏览器运行),就是这样。我建议阅读有关如何开始使用 ajax 的教程。
  • 我已经更新了我的答案@Supertod,并为您提供了一个示例,说明您可以如何做到这一点。我希望这可以帮助你。请注意,我做了一些不知道数据是如何存储的假设(即 id 是 int,is.. 都是 bools 等等)。您可能需要更改内容以与您的数据相对应。
猜你喜欢
  • 1970-01-01
  • 2021-05-26
  • 2021-12-08
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2019-12-20
  • 2018-12-25
  • 1970-01-01
相关资源
最近更新 更多