8vius
8vius

Reputation: 5836

JQuery AJAX not sending file with form

I have the following AJAX function with JQuery:

var formData = $('#FonykerEditForm').serialize();    
$.ajax ({
    type: 'POST',
    url: '<?php echo $html->url('/fonykers/edit',true); ?>',
    data: formData,
    dataType: 'json',
    success: function(response) {
        message.html(response.msg);
        message.fadeIn();
        if(!response.ok) {
            message.removeClass('success');
            message.addClass('error');
        } else {
            message.removeClass('error');
            message.addClass('success');
            username = $('#FonykerUsername').val();
            email = $('#FonykerEmail').val();
        }

        $('#save-account-button').removeAttr('disabled');
        $('.input-text').removeClass('ok');
        $('.input-combo').removeClass('ok');
    },
    error: function (xhr, ajaxOptions, thrownError){
        alert(xhr.statusText);
        alert(thrownError);
        $('#save-account-button').removeAttr('disabled');
    }
});

The problem I'm having is that a type file field in my form is not getting submitted along with the rest of the data of the form, how can I include the file in the data of the ajax request?

Upvotes: 1

Views: 7396

Answers (3)

asHkER
asHkER

Reputation: 435

I tried this link and this works fine for me.

http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

Example:

  $( '#my-form' ).submit( function( e ) {
  $.ajax( {
    url: 'http://host.com/action/',
    type: 'POST',
    data: new FormData( this ),
    processData: false,
    contentType: false
  } );
  e.preventDefault();
} );

Upvotes: 9

HyderA
HyderA

Reputation: 21411

Like I said in the comment above, sending files via ajax is not straightforward. If you wish to try it anyway. The normal approach I've seen is to create a new iframe, add a file input field to it, select your file and submit it programmatically. This way, the iframe does the submission in the background.

Take a look at how this plugin does it:

https://github.com/valums/file-uploader/blob/master/client/fileuploader.js#L995

https://github.com/FineUploader/fine-uploader

Upvotes: 2

Varun Achar
Varun Achar

Reputation: 15129

Basically an AJAX will submit data in the form of key/value pairs.. Since files are binary data, you can't submit files using Ajax.. You'll need to submit the data using a standard form submit instead and on the server since accept a form/multipart

Upvotes: 1

Related Questions