0

Following is my ajax call in which I am sending my form data to a PHP page and diplaying the messages accordingly. The issue I am facing is with ajax seralize() post my file is not getting posted and send.php gives error in response Notice: Undefined index: file . Kindly let me know what is an appropriate way to post form data with ajax enctype="multipart/form-data" so files can be send as a post too via ajax.

var post_data = $( "#form" ).serialize();

$.ajax({
            type: "POST",
           url: "send.php",
            async: false,
            data: post_data,
            success: function(html){

              if (html.indexOf("filerror") != -1)
              {
              alert('error');
              }

              else if(html.indexOf("true") != -1)
              {
                alert('true');
              }
              else if (html.indexOf("false") != -1)
              {
                  alert('false');

              }


            },
            beforeSend:function()
            {



            }
        });
user3027531
  • 282
  • 1
  • 5
  • 20

1 Answers1

0

$( "#form" ).serialize() just get form fields values, not its content(for file). If you want to get file content works with files control field:

var $fileInput = $('input[type="file"]');
var files = $fileInput.get(0).files;

You must work with variable files with FileReader constructor. But better for file uploading by AJAXuse plugins, for example this.

Alex
  • 11,115
  • 12
  • 51
  • 64
  • Check `FileReader` [support](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) also. – Alex Dec 27 '13 at 12:44
  • And if you will use `jQuery File Upload` plugin get the basic example [page](http://blueimp.github.io/jQuery-File-Upload/basic.html) source code for implementation it. – Alex Dec 27 '13 at 12:47
  • Better will be upload image by ajax via plugin, ajax will return the id of uploaded image. You will append hidden form field with this image id and name `images[]`. After this you can work with form by `serialize` method. – Alex Dec 27 '13 at 12:50
  • kindly let me know how to post a file with `id=file` via ajax as per your method? Also will it work in all browsers? – user3027531 Dec 27 '13 at 13:05
  • If you use `jQuery File Upload` plugin, code will work in all browsers (modern and IE 6+). See source of [this](http://blueimp.github.io/jQuery-File-Upload/basic.html) basic example page for more info. – Alex Dec 27 '13 at 15:02
  • hey I used `var formData = new FormData(document.getElementById('form'));` but its not working in internet explorer any idea how to do it for IE – user3027531 Dec 27 '13 at 15:16
  • Also I cannot use any plugin cause I am not uploading file i am send it in an email. – user3027531 Dec 27 '13 at 15:27