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";
}
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?– programmer2016