2

I'm creating an ajax upload file. I have written my upload code using PHP and it works fine. The problem is when I use $.ajax{}. The form data cannot be received by my upload.php. Here is my code.

function pleaseUpload(){
$(document).ready(function(){
        //var fd=new FormData($("form#form_upload_1"));
        var fd = new FormData();
        fd.append( "file", $("#edit_first [type=file]")[0].files[0]);
        fd.append( "hid", $("#form_upload_1 [type=hidden]").val());
        alert(fd);
        $("#image_1").html("");
        $.ajax( {
          type: 'POST',
          url: 'save_picture.php',
          data: fd,
          processData: false,
          contentType: false,
          cache: false,
          success: function(data){
            $("#image_1").html(data);
          }
        });
});

}

<form id='form_upload_1' enctype='multipart/form-data' name='form_upload_1' method='post' action=''>    
   <div id='edit_first' class='upload_button_wrapper'>
    <input id='edit_first' class='upload_button' type='file' onchange='pleaseUpload()' name='file'/>
    <input type='hidden' name='hid' value="first" />
   </div>
</form>
user3422210
  • 53
  • 1
  • 5

1 Answers1

0

If you want to pass a form to a form data object you have to do it in the constructor

var fd = new FormData($("#form_upload_1")[0]);

notice I pass the HTMLFormElemnt and not the jQuery object that encapsulates it.

The append method takes strings/Blobs/Files i.e. form field data

var fd = new FormData();
fd.append( "file", $("#edit_first")[0].files[0]);
fd.append( "hid", $("#form_upload_1 [type=hidden]").val());

Also you should know that the id attribute for html elements should be unique per document.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • I have edited my javascript. Still it wasn't posted to the php file. Do you think the "onchange" attribute of the file affected the script from posting? – user3422210 Aug 18 '14 at 05:04
  • @user3422210 this might be because you have two elements with the same id. Try using the one with the form constructor, or fix your markup. – Musa Aug 18 '14 at 13:34