vulkan vulkan - 5 months ago 7
PHP Question

change file(image) input ajax can't post file

Ajax can not send files (jpg-png). I could not solve the problem.

form code

<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="img">
<button id="post-img">update</button>
<!-- input hidden !! -->
<input type="file" name="img" id="a-img" style="visibility:hidden">
</label>


ajax:

$('#a-img').change(function(){
var photo = $('form').serialize();
$.ajax({
url:'upload.php',
data: photo,
success:function(data){
alert(data);
}
});
});


php code:

if($_FILES){
echo "file ok";
}else{
echo "no file";
}


callback : "no file";

Answer

Add id frm_send_img to the form.

<form action="upload.php" id="frm_send_img" method="post" enctype="multipart/form-data">
 <label for="img"> 
  <button id="post-img">update</button>
  <!-- input hidden !! -->
  <input type="file" name="img" id="a-img" style="visibility:hidden">
</label>

Change script like below.

 $('#a-img').change(function(){
            var photo = new FormData($("#frm_send_img")[0]);

            $.ajax({
                url: "upload.php",
                type: "POST",
                data: photo,
                async: false,
                success: function (msg) {
                    alert(msg)
                },
                cache: false,
                contentType: false,
                processData: false
            });

            e.preventDefault();
        });
Comments