Upload image using ajax

Asked

Viewed 46 times

0

I wanted to insert an image on the server using AJAX. I have tried to do it in a number of ways but I am unable to upload the image to the server. If anyone can find a solution, I would appreciate it!

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"; 
}

1 answer

0

You need to instantiate an object of the type FormData, put the file inside it and then refer it to $.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); 
    });
});
  • if you do so, what formData will contain will be [object FormData]. By the way I also ask why to use formData (never used). It should only be used in file cases?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.