2016-07-28 8 views
0

У меня есть динамический стол, который отправляет весь входной текст в мою базу данных ajax.Как загрузить входной файл с помощью 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> 

И есть мой "ajout-ingredient.php" страница:

<?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-component.php О, и моя функция загрузки файла работает, потому что я использовал ее до:

Заранее благодарен!

+0

Для загрузки файлов с помощью ajax вам необходимо изучить объект FormData. http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload и https://developer.mozilla.org/en-US/docs/Web/API/FormData – neilsimp1

+0

Вы уязвимы для [sql injection атак ] (http://bobby-tables.com) –

+0

@ neilsimp1 Спасибо, я хочу проверить это :) – Lanaya

ответ

0

Вы можете сделать это легко и без отправки формы, но сначала вы должны обернуть все входы, которые вы хотите передать внутри элемента формы

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

Тогда вы могли бы использовать FormData передать все входы в ваш PHP скрипт (в том числе файлов) с использованием AJAX

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, 
..... 

Если по какой-то причине вы не хотите иметь form элемент в вашем HTML вы можете просто создать 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 
Смежные вопросы