如何使用没有表单的ajax上传输入文件?

时间:2016-07-28 15:10:52

标签: javascript php jquery ajax upload

我有一个动态表,它通过ajax将所有输入文本发送到我的数据库。

到目前为止这是我的代码..

<script language="javascript" type="text/javascript">

var i = 2; //This varaible serves to always be "positionned" on the last row

function test(select) {
       //Here I'm cheking that somes inputs are not empty
            /*if (select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[0].firstChild.value == "") {
                alert("Veuillez rentrer un nom d'ingrédient");
            }
            else if (select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value == "") {
                alert("Veuillez rentrer un code pour l'ingrédient");
            }*/

            //Now I'm selecting all values from input in my table and post them to another page with ajax
            var id_produit = select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[8].firstChild.value; //I need this variable to create rows
            var data = 'nom_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[0].firstChild.value
            + '&code_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value
            + '&conditionnement_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[2].firstChild.value
            + '&fiche_technique_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[3].firstChild.files[0] // <<<<< THIS IS MY INPUT FILE !
            + '&commentaire_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[7].firstChild.value
            + '&id_produit='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[8].firstChild.value;
            $.ajax({
                url: "ajout-ingredient.php",
                type: "POST",
                data: data,
                success: function()
                {
                    alert(data);
                    addligne(select, id_produit); //The function that creates rows
                    i++;

                },
                error: function (xhrReq, textstatus, errorThrown) {
                            alert(xhrReq.status);
                            alert(errorThrown);
                        }
            });
            return false;
            /*}*/
    }

function addligne(select, id_produit) { //The function to create rows
<?php
$usine = $GLOBALS['usine']; //By doing this, I'm starting to create a <select>
?>
var usine = <?php echo json_encode($usine) ?>;
    var element2 = document.createElement("select");

    for (var j = 0; j < usine.length; j++) {
    var option = document.createElement("option");
    option.value = usine[j].id_usine;
    option.text = usine[j].nom_usine;
    element2.appendChild(option);
    }

    var table = select.parentNode.parentNode.parentNode.parentNode.tBodies[1]; //Selecting the table where I want to create rows
    var row = table.insertRow(-1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    var cell6 = row.insertCell(5);
    var cell7 = row.insertCell(6);
    var cell8 = row.insertCell(7);
    var cell9 = row.insertCell(8);


    cell1.innerHTML = '<input type="text" name="nom_ingredient" value="" placeholder="Ingredient '+i+'"/>';
    cell2.innerHTML = '<input type="text" name="code_ingredient" value=""/>';
    cell3.innerHTML = '<input type="text" name="conditionnement_ingredient" value=""/>';
    cell4.innerHTML = '<input type="file" name="fiche_technique_ingredient"/>';
    cell5.innerHTML = '<input type="file" name="certificat_ingredient"/>';
    cell6.innerHTML = '<input type="file" name="photo_ingredient"/>';
    cell7.appendChild(element2);
    cell8.innerHTML = '<input type="text" name="commentaire_ingredient"/></td>';
    cell9.innerHTML = '<input type="hidden" name="id_produit" value="'+id_produit +'" />';
}


</script>

还有我的&#34; ajout-ingredient.php&#34;页面:

<?php
require_once (__DIR__.'/../base/singleton.php');
if($_POST)
{
$nom_ingredient=$_POST['nom_ingredient'];
$code_ingredient=$_POST['code_ingredient'];
$conditionnement_ingredient=$_POST['conditionnement_ingredient'];
$commentaire_ingredient=$_POST['commentaire_ingredient'];
$id_produit=$_POST['id_produit'];


    try {
        $PDO = myPdo::getInstance();
    }
    catch (PDOException $e) {
        die('Une erreur interne est survenue');
    }
    $req = $PDO->query('INSERT INTO ingredient (nom_ingredient, code_ingredient, conditionnement_ingredient, commentaire_ingredient, id_admin) 
                        VALUES ("'.$nom_ingredient.'", "'.$code_ingredient.'", "'.$conditionnement_ingredient.'", "'.$commentaire_ingredient.'", "1")');
    $last = $PDO->lastInsertId();
    $req2 = $PDO->query('INSERT INTO composer_produit_ingredient (id_ingredient, id_produit) VALUES ("'.$last.'", "'.$id_produit.'")');


    //Part to upload a file
    //This is where I'm stuck..

    $select_nom = $PDO->query('SELECT nom_societe_client from client as c 
                        JOIN demande as d on c.id_client = d.id_client
                        JOIN composer_demande_produit as c_d_p on d.id_demande = c_d_p.id_demande
                        JOIN composer_produit_ingredient as c_d_i on c_d_p.id_produit = c_d_i.id_produit
                        Where id_ingredient = "'.$last.'" ');
    $select_nom = $select_nom->fetchColumn();
    $select_nom = str_replace(' ', '', $select_nom);
    $dossier = $select_nom;
    $chemin_base = "../upload/";
    $chemin_final = $chemin_base . $dossier;
            if (is_dir($chemin_final)) {
            }
            else{
                mkdir($chemin_final);
            }
            $_FILES['name'] = str_replace(' ', '', $_FILES['name']);
            $test = $chemin_final . "/";
            $fichier = $test.$_FILES['name'];
            if(is_uploaded_file($_FILES['tmp_name'])) {
                $chemin = $chemin_final."/".$_FILES['name'];
                $today = date("Y-m-d H:i:s");
                $req = $PDO->prepare('INSERT INTO document (chemin_doc, type_document, date_upload, id_ingredient) 
                        VALUES ("'.$chemin.'", "fiche_technique_ingredient", "'.$today.'", "'.$last.'")');
                $req ->execute();
                if(!move_uploaded_file($_FILES['tmp_name'], $fichier)) {
                    echo "Problème : Impossible de déplacer le fichier dans son répertoire de destination.";
                    exit;
                }
            }
}

else {
}

?>

所以每个值都正确地进入我的数据库,但我仍然无法上传文件。 我想这是因为我无法将输入文件从我的脚本传递到ajout-ingredient.php页面 哦,我上传文件的功能有效,因为我之前使用过她:)

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以在不提交表单的情况下轻松完成此操作,但您应首先将所有要输入的输入包装在表单元素中

<form id="your_form" method="post" enctype="multipart/form-data">...</form>

然后你可以使用FormData使用AJAX将所有输入传递给你的php脚本(包括文件)

test(select) {

....
var your_form = $('#your_form')[0];
var formData = new FormData(your_form);
.....
$.ajax({
            url: "ajout-ingredient.php",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
.....

如果出于某种原因你不想在你的html中有form元素,你可以创建formData对象,然后逐个追加你想要的数据

var formData = new FormData();

var code_ingredient=select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value;

formData.append("code_ingredient", code_ingredient);                   //to append your values
....
formData.append('certificat_ingredient', $('input[name="certificat_ingredient"]')[0].files[0]);  //to append your files