4

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

vciloglu
  • 526
  • 2
  • 7
  • 19

2 Answers2

2

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();
        });
LoneRanger
  • 117
  • 8
1

You can do like this:

 $('#a-img').change(function(){
        var frmData = new FormData();
        frmData.append('file', $('#a-img')[0].files[0]);
        $.ajax({
            method: "POST",
            url: "upload.php",
            data: frmData,
        }).done(function (msg) {
          //logic after success
        });

You can access images on server as usual:

if (isset($_FILES["img"]["name"]) && $_FILES["img"]["name"] != "") {
     echo "image validation and uploading";
    }else{
     echo "no file uploaded"; 
    }
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90