PHP : insert into database with ajax

标签 php ajax database select insert

实际使用 Ubuntu(使用 PHP 语言), 我有一个 PDF 文件,我将其转换为文本,然后我进行 preg_match 以提取我需要的数据。

在此之后,我将我的数据行放入下拉列表中

问题:我想使用 Ajax(据我所知)获取所选选项并将其保存到我的数据库中

我已经阅读了很多关于这个问题的主题,但都是徒劳的......

这是我的一段代码,它可能更具体!

我的 PHP 文件:

$file = fopen($fichier_txt, 'r+');

if ($file)
{
    $lines = array();
    $pattern_GC = '/N°.*\d{4}(\s?\s?[\w\s]*)(\d{5})\s?(\w+)\W+/isU';
    $fichier_txt_content = file_get_contents($fichier_txt);
    $regex_GC = preg_match_all($pattern_GC, $fichier_txt_content, $match_GC);
// Match regroupant nom/prenom + adresse
$match_un = explode(PHP_EOL, $match_GC[1][0]);
$match_nom_prenom = $match_un[2];
$match_adresse = $match_un[3];
// Match CP
$match_deux = $match_GC[2][0];
// Match ville
$match_trois = $match_GC[3][0];

$opt = array($match_nom_prenom, $match_adresse, $match_deux, $match_trois);
$i = 0;?>
<html>
        <form>
            <select name="selectBox" class="drop" id="Combobox1" onchange="saveToDatabase(this.value)">
            <?php foreach($opt as $val) {?>
                <option value="$opt[$i]"><?=$val?></option>
            <?php } ?>
            </select>
        </form>
</html>

我的 formulaire_2_test.php 文件:

<?php
    // Database connection to save form lines (PDO)
            try
            {
                $PDO = new PDO('mysql:host=localhost;dbname=autofill_data', 'root', 'password');
            }
            catch (Exception $e)
            {
                die('Erreur : ' . $e->getMessage());
            }

        // Get selected option and save into database
            $selectedOpt = $_POST['selected'];
            //exit($selectedOpt); --> I put this line in comments since I don't use it everytime.


            $req = $PDO->prepare("INSERT INTO data_lines(idDistributeur, numLigne, libelle) VALUES(1, 2, :selectedOpt)");
            $req->bindParam(':selectedOpt', $selectedOpt);
            $req->execute($selectedOpt);
            $data = $req->fetchAll();
        }

    ?>

现在这是我的 Ajax 脚本(我是 JS 的新手,我知道一些巨大的错误可能会突然出现在你面前,对此感到抱歉,还有我的法语命名......)

Ajax:(位于我的 php 文件中)

<style>
    .ui-autocomplete
    {
        cursor:pointer;
        height:120px;
        overflow-y:scroll;
    }
</style>

<script>

    function saveToDatabase(selectedValue)
    {
        var select = selectedValue;
        select = $(this).serialize();
        $('#Combobox1').on("change", function ()
        {
            // POST to php script
            $.ajax
            ({
                type: 'POST',
                url: 'formulaire_2_test.php',
                data:{selected:this.value}
            }).then(function(data){alert(data)});
        });
    }

    $(document).ready(function()
    {
        saveToDatabase();
    });

</script>

我用粗略的值测试了我的 PDO 连接,它确实有效,但我想知道我如何将我的 php 变量传递给它(我不确定是否使用 $_POST 检索此数据因为我不刷新任何页面...) 我还尝试将 INSERT 插入表 VALUES(:name, 2, 3) 但它也没有用...... 我正朝着正确的方向前进吗? 你会如何考虑这样做?

PS:我的下一步是从以下下拉列表中删除所选选项(以便在用户填写订阅表格时节省一些宝贵的时间)。

编辑 11 月 24 日:我需要我的“Fais ton choix”选项作为默认值出现在我的下拉列表中,但不在列表选项中:autofill

我的上一期:我想删除下拉列表中的选定选项,因此它不会出现在另一个后续下拉列表中。 这是我试过的代码(不起作用):

function removeSelected(value)
        {
                $('.drop').change('select', function ()
                {
                    // Definition des variables
                    var value = this.value;
                    var id = this.id;
                    //  We del selects with a != id containing options with the same value of the selected one.
                    $("select:not(#" + id + ") option[value='" + value + "']").hide()
                });
        }

我也尝试过使用 .remove() 而不是 .hide() 但没有成功!

提前致谢

问候,

斯泰里奥·康托斯。

最佳答案

将此注释后面的 PHP 代码://Database connection to save form lines (PDO) 放入不同的文件中。从您的 jQuery ajax 函数中,将 url 设置为这个新的 PHP 文件。同时将 data: 'selected=' + select 更改为 data: {selected: select}

现在在您的 PHP 文件(新文件)中设置 $selectedOpt = $_POST['selected'];

您的 PHP 代码的最后一点应该如下所示:

$req = $PDO->prepare("INSERT INTO data_lines(idDistributeur, numLigne, libelle) VALUES(1, 2, :selectedOpt)");
$req->bindParam(':selectedOpt', $selectedOpt);
$req->execute();

编辑:javascript 修复

你的 JS 应该是:

$(document).ready(function () {
    $('#Combobox1').on('change', function () {
        $.ajax({
            method: 'POST',
            url: 'save-selection.php',
            data: {
                // this is a reference to the select box, which means
                // this.value is the value of the select box
                selected: this.value
            }
        }).then(function (data) {
            alert(data);
        });
    });
});

关于您更新后的要求,您只需在 ajax 调用下添加 $(this).children(':selected').remove(); 即可。不需要另一个 change 监听器。但是,当用户选择一个选项时,它会立即将其删除,因此选择框只会显示第一个选项。试试看,您就会明白我的意思。

关于PHP : insert into database with ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765712/

相关文章:

javascript - 重复使用代码,无需提交两次表单

jquery - 在新窗口中显示 POST AJAX 响应

javascript - 通过 Ajax 验证 django html 模板中至少选中一个复选框

sql - ORA 01114 - 将 block 写入文件的 IO 错误

stored-procedures - 为什么(以及何时)使用存储过程?

database - 为什么在sql*plus等查询工具中运行查询时不显示警告信息?

PHP 将变量传递给 array_walk_recursive

PHP:在线离线状态

php - 如果设置了数组,做点什么?

php - 通过 AJAX 将关联数组传递给 PHP