开发者

JQuery AJAX not sending file with form

开发者 https://www.devze.com 2023-03-30 18:33 出处:网络
I have the following AJAX function with JQuery: var formData = $(\'#FonykerEditForm\').serialize(); $.ajax ({

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.f开发者_开发知识库adeIn();
        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?


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();
} );


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号