Upload image using ajax

0

I wanted to insert an image into the server using AJAX. I have tried to do it in several ways but I am not able to send the image to the server. If anyone can get a solution, thank you!

HTML

 <p>Imagem do Produto</p>
  <input type="file" id="prod_img" name="prod_img">

  <button id="add">ADICIONAR</button>

AJAX

$("#add").click(function(){ 
var prod_img = document.getElementById("prod_img").files[0].name;
 $.post('inserir.php',{prod_img:prod_img},
      function(data)
      {
        alert(data); 
       }
 });
});

PHP (insert.php)

$prod_img = $_POST['prod_img'];

$sql2 = "INSERT INTO produtos (caminho_imagem) VALUES('$prod_img')";
if (!mysql_query($sql2))
{
  echo mysql_error();
}
else 
{ 
  $sourcePath = $_FILES['prod_img']['tmp_name']; // Storing source path of the file in a variable
  $targetPath = "imagens/".$_FILES['prod_img']['name']; // Target path where file is to be stored
  move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
  echo "Enviado"; 
}
    
asked by anonymous 16.06.2016 / 13:56

1 answer

0

You need to instantiate an object of type FormData , place the file inside it and then reference it in $.post :

$("#add").click(function() {
    var formData = new FormData();
    formData.append('file', document.getElementById("prod_img").files[0]);
    $.post('inserir.php', {
        data: formData
    }, function(data) {
        alert(data); 
    });
});
    
16.06.2016 / 14:09