当试图插入数据库时,jQuery keyup函数停止工作。

时间:2022-11-22 15:45:21

This is a weird problem and I'm not sure how to approach it.

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

At the moment I'm trying to have the user enter an ingredient - a list of ingredients appears as you type with buttons next to them to add them which should insert them into SQL database.

目前,我正在尝试让用户输入一个成分——当您键入旁边的按钮时,会出现一个成分列表,以便将它们添加到SQL数据库中。

The list population ceases to function when I uncomment

当我取消注释时,列表填充将停止工作

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

In the .click function of the add button. Which is strange because it's like the .keyup function just stops working.

在.click函数的add按钮。这很奇怪,因为它就像。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>

1 个解决方案

#1


2  

You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)

不能像现在这样在javascript中嵌入保存查询。这是一个需要执行的服务器端函数,并返回一个结果(几乎与使用get_配料函数一样)。

My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.

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

in saveingredients.php:

在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);

?>

A sample AJAX function:

一个示例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);
        }
    });
}

#1


2  

You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)

不能像现在这样在javascript中嵌入保存查询。这是一个需要执行的服务器端函数,并返回一个结果(几乎与使用get_配料函数一样)。

My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.

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

in saveingredients.php:

在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);

?>

A sample AJAX function:

一个示例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);
        }
    });
}