插入数据后刷新选项

时间:2018-09-24 12:57:57

标签: php jquery html ajax

这样列出数据:

    <select class="custom-select col-md-10" id="routeList" size="8">
        <option selected>Choose...</option>
        <?php
        include( '../cnn.php' );
        $query= $db_con->query( "select routeName, id from tbroutes order by routeName" );
        $routes= $query->fetchAll();
        foreach ( $routes as $route) {
           echo "<option value=\"" . $route[ 'id' ] . "\">" . $route[ 'routeName' ] . "</option>";
       }
       ?>
   </select>

我有一个文本输入和按钮。单击按钮,将新路由添加到数据库。

$('#btnSave').click(function() {
        var route = $('#textRoute').val();
        $.post("addRoute.php",{
            route: route
        }, function(addRoute){});
    });

addRoute.php

<?php
if ( $_POST ) {
    $route = $_POST[ 'route' ];
    include "../cnn.php";

    $query = $db_con->query( "insert into tbroutes (routeName) values ('$route')", PDO::FETCH_ASSOC );
} else {
    header( "location:index.php" );
}
?>

我要做的是在插入新路线后刷新选项(重新列出)而不刷新页面。

我对Ajax不太了解,您能帮我吗?

1 个答案:

答案 0 :(得分:1)

使您的PHP脚本返回插入数据库中的新ID。

if ( $_POST ) {
    $route = $_POST[ 'route' ];
    include "../cnn.php";

    //$query = $db_con->query( "insert into tbroutes (routeName) values ('$route')", PDO::FETCH_ASSOC );
    //THIS IS AT RISK FOR SQL INJECTION, safer to use the following:

    $query = $db_con->prepare("INSERT INTO tbroutes (routeName) VALUES (?)");
    $query->execute([$route]);
    //Notice that I capitalize non-variable words in the query, this makes it easier to read

    echo json_encode(["success" => true, "uid" => $db_con->lastInsertId(), "route" => $route]); //assuming your using PDO

} else {
    echo json_encode(["success" => false]);
}

(请注意,您的header( "location:index.php" );在这里实际上不会做任何事情,因为它是由ajax加载的。)

如果插入是否成功,我也要返回。如果插入成功,我也会返回路线,这是我个人的偏爱,因为我认为使用返回数据比使用不同位置的数据更容易。

我将数据作为JSON字符串返回,因为这是使用Javascript中的数据的一种非常简单的方法。

现在,在ajax调用中捕获响应

$('#btnSave').click(function() {
    var route = $('#textRoute').val();
    $.post("addRoute.php",{
        route: route
    }, function(addRoute){
        addRoute = JSON.parse(addRoute); //this may or may not be necessary, depending on your environment
        if(addRoute.success) {
            $('#routeList').append(
                $('<option>', {value: addRoute.uid, text: addRoute.route})
            );
        } else {
            //failed to insert
        }
    });
});