简体   繁体   English

php:使用ajax插入数据库

[英]php : insert into database with ajax

actually working on Ubuntu (working PHP language), I have a PDF file that I convert into text, then I preg_match in order to extract the data I need. 实际上是在Ubuntu (工作于PHP语言)上工作的,我有一个PDF文件,我将其转换为文本,然后我进行preg_match以便提取所需的数据。

After this, I put my data lines into a drop-down list . 之后,我将数据行放入一个下拉列表中

PROBLEM : I want, using Ajax (as far as I understood), to get the selected option and save it into my database . 问题:据我所知,我想使用Ajax 获取选定的选项并将其保存到我的数据库中

I've read many topic about this issue, in vain... 我已经读过许多关于这个问题的话题,但都是徒劳的。

Here's a piece of my code, it may be more concret ! 这是我的一段代码,可能更具体!

My PHP File : 我的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>

My formulaire_2_test.php file : 我的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();
        }

    ?>

And now here is my Ajax script (i'm new in JS and I know some enormeous mistakes may pop in front of you, sorry about that, and about my french naming...) 现在是我的Ajax脚本(我是JS的新手,我知道您面前可能会冒出一些巨大的错误,对此感到抱歉,以及我的法语命名...)

Ajax : (located in my php file) 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>

I tested my PDO connection with rough values, and it does work, but I wonder how I could pass my php variable into it (I'm not sure about using $_POST to retrieve this data since I don't refresh any page...) I also tried with INSERT into table VALUES(:name, 2, 3) but it didn't work either... Am I heading in the right direction ? 我用粗略的值测试了我的PDO连接,它确实起作用了,但是我想知道如何将php变量传递给它 (我不确定使用$ _POST来检索此数据,因为我不刷新任何页面。 。)我还尝试了将INSERT插入到表VALUES(:name,2,3)中,但还是没有用...我朝着正确的方向前进吗? How would you consider doing this ? 您会如何考虑?

PS : My next step after this would be to remove the selected option from the following dropdown lists (in order to save the user some precious minutes as he fills a subscription form). PS:此后的下一步是从以下下拉列表中删除选定的选项(以便在用户填写订阅表单时为用户节省一些宝贵的时间)。

EDIT Nov 24th : I need my "Fais ton choix" option to appear on my dropdown as a default value, but not in the list options : 编辑11月24日:我需要将“ Fais ton choix”选项作为默认值显示在我的下拉列表中,但不会在列表选项中显示: 自动填充

My last issue : I want to remove the selected option of the dropdown, so it won't appear in another following dropdown. 我的最后一个问题:我想删除下拉菜单的选定选项,因此它不会出现在另一个下拉菜单中。 Here's the code I tried (doesn't work) : 这是我尝试的代码(不起作用):

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()
                });
        }

I also tried with .remove() instead of .hide() without success ! 我也尝试了.remove()而不是.hide(),但没有成功!

Thanks in advance, 提前致谢,

Regards, 问候,

Stelio Kontos. Stelio Kontos。

You can't directly send information from Javascript to PHP. 您不能直接将信息从Javascript发送到PHP。 You have to use some REST API or some HTTP webservice that manages HTTP request and then insert into your database. 您必须使用一些REST API或一些管理HTTP请求的HTTP Web服务,然后将其插入数据库中。

You can program a REST API like this and then simply use $_POST['selected'] to retrieve the parameter of the POST request you did with JQuery. 您可以像这样编写REST API,然后只需使用$ _POST ['selected']来检索您使用JQuery执行的POST请求的参数。

Also, I recommend you to use minAjax 另外,我建议您使用minAjax

Put the PHP code that follows this comment: // Database connection to save form lines (PDO) into a different file. 将带有以下注释的PHP代码放入: // Database connection to save form lines (PDO)到另一个文件中。 From your jQuery ajax function, set the url to this new PHP file. 从jQuery ajax函数中,将url设置为此新的PHP文件。 Also change data: 'selected=' + select to data: {selected: select} . 同时更改data: 'selected=' + select data: {selected: select}

Now in your PHP file (the new one) set $selectedOpt = $_POST['selected']; 现在在您的PHP文件(新文件)中,设置$selectedOpt = $_POST['selected']; .

The last bit of your PHP code should look this this: PHP代码的最后一部分应如下所示:

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

Edit: javascript fixes 编辑:javascript修复

Your JS should be: 您的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);
        });
    });
});

Regarding your updated requirement, you can just add $(this).children(':selected').remove(); 关于更新的需求,您可以只添加$(this).children(':selected').remove(); under your ajax call. 在你的ajax电话。 No need for another change listener. 无需其他change侦听器。 However, when a user selected an option, it will instantly remove it so the select box will only ever show the first option. 但是,当用户选择一个选项时,它将立即将其删除,因此选择框将仅显示第一个选项。 Try it and you will see what I mean. 试试看,您会明白我的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM