0

I'm submitting a form through jQuery and all my form data working fine except File Field. When I use without jQuery then file field is also working fine. Below is my code,

jQuery

jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('#submit_data').click(function(e){
    e.preventDefault();
    var error = false;
    var name = jQuery('#name').val();
    if(name.length == 0){
        var error = true;
        jQuery('#name_error').fadeIn(500);
    }else{
        jQuery('#name_error').fadeOut(500);
    }
    if(error == false){
        $('#submit_data').attr({'disabled' : 'true', 'value' : 'Submitting...' });
        $.post("submit.php?action=add_user", $("#add_user").serialize(),function(result){
            if(result == 'sent'){
                 $('#submit_data').remove();
                $('#submit_success').fadeIn(500);
            }else{
                $('#submit_fail').fadeIn(500);
                $('#submit_data').removeAttr('disabled').attr('value', 'Submit');
            }
        });
    }
});    
});

HTML

<form action="" method="post" enctype="multipart/form-data" id="add_user">
<input type="test" id="name" name="name" />
<input type="file" id="file" name="file" />
<input type='submit' value='Submit' class="button" id='submit_data'>
</form>

In my PHP code I just want to echo $image =$_FILES["file"]["name"]; but it doesn't pass value and other fields of that form is working perfect.

Arif
  • 1,222
  • 6
  • 29
  • 60
  • 1
    .serialize can't be used to send files. – Kevin B Feb 05 '14 at 21:04
  • possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) (note the answers that don't involve plugins, http://stackoverflow.com/a/8758614/400654) – Kevin B Feb 05 '14 at 21:05

3 Answers3

0

serialize() can't send files.

I suggest using " FormData " for uploading files with Ajax function:

if( window.FormData !== undefined ) 
    //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12 <- wil support XHR too
        {

            var formData = new FormData($('#yourForm')[0]);
            $.ajax({
                url: 'fileUpload.php',  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },

                beforeSend: function(){

                },
                success: function(response){

                },
                error: function(xhr, ajaxOptions, thrownError){
                    console.log(thrownError);
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        }

FormData wil support multi file upload too and you can easily add your own fields by using:

formData.append("fieldname",value1);

Add to your Form tag the attribute:

enctype="multipart/form-data"

Should work great!

NOTE: You may find that the FILES array is empty on server side page - In this case you need to make sure your server configuration allows file uploads, size limit of file upload is enough, post time
is enough etc....

The best way to begin is to make sure that file uploads is allowed and then testing with very
small files to be sure everything in your code is OK.

Shlomi Hassid
  • 6,500
  • 3
  • 27
  • 48
0

You can't send a file with .serialize(). Instead you can use FormData api to do it.

if(error == false){
    var file =  $("#file")[0].files[0];

    var formData = new FormData($("#add_user"));
    formData.append("name", name);
    formData.append("file", file);
    $('#submit_data').attr({'disabled' : 'true', 'value' : 'Submitting...' });

    $.ajax({
      url: 'submit.php?action=add_user',
      type: 'POST',
      // Form data
      data: formData,
      success: function(data){
        $('#submit_data').remove();
        $('#submit_success').fadeIn(500);
      },
      error: function(){
        $('#submit_fail').fadeIn(500);
        $('#submit_data').removeAttr('disabled').attr('value', 'Submit');     
      },

      //must keep false
      cache: false,
      contentType: false,
      processData: false 
    });
 }
VVLeon
  • 399
  • 3
  • 8
-2

You can't submit a file through ajax. I would suggest this plugin to quickly do what you're trying to do

http://malsup.com/jquery/form/