I have a HTML Form so I can update the profile image of the users by my own.
I have the AJAX that sends the image via POST to PHP and in turn PHP uploads it to the server. The problem is that, although the form allows me to choose the file, when selecting the image (onchange), it does not send the image in question.
I already tried to do it also doing a trigger(submit)
with input type submit
, but exactly the same as using on(change)
with input type file
.
I leave the scripts, if someone can tell me what I'm doing wrong to modify it, I thank you in advance.
HTML Script
<form enctype="multipart/form-data" class="form-img" method="POST">
<div class="row" style="margin: 0px; font-size: 18px;">
<div class="col-md-4">
<img width="100%" height="auto" src="fotos/<?php echo $_SESSION['logo']; ?>"><br>
</div>
<div class="col-md-8">
<label style="display: block;">Seleccione una imagen de perfil:</label>
<div hidden><input name="image" type="file"></div>
<div class="btn-only blue upload" style="margin: 0px;">Buscar</div>
<span class="img-status"></span>
</div>
</div><hr>
</form>
AJAX script (jQuery)
$(".upload").on("click", function(){
$("[name=image]").trigger("click");
});
$("[name=image]").on("change", function(){
$.ajax({
url: "functions/cambiar_imagen.php",
type: "post",
data: $(".form-img").serialize(),
success: function(e){
alert(e);
}
});
});
PHP Script
<?php
session_start();
include("serverconfig.php");
include("codificar_clave.php");
include("log.php");
$target_path = "../fotos/";
$target_path = $target_path.basename($_FILES["image"]["name"]);
$temp_path = $_FILES["image"]["tmp_name"];
if(move_uploaded_file($temp_path, $target_path)){
echo "El archivo ".basename($temp_path). " ha sido subido";
} else {
echo "Ha ocurrido un error, trate de nuevo!";
}
?>