the form:

<form action="#" enctype="multipart/form-data" method="POST"> <input id="photos_upload" multiple="true" name="userPhotos[]" accept="image/jpeg,image/png,image/gif" type="file"> </form> 

JS script:

 $('#photos_upload').change(function(){ console.log('uploading'); var formData = new FormData($(this).parents('form')[0]); $.ajax({ url: 'albums/addPhoto', type: 'POST', data: formData, cache: false, contentType: false, processData: false, xhr: function() { var myXhr = $.ajaxSettings.xhr(); return myXhr; }, success: function (data) { alert("Data Uploaded: " + data); }, error:function () { console.log('uploading'); } }); event.preventDefault(); }); 

Without JS, it works fine, but it is impossible to transfer data via ajax

  • Here is the answer, everything is detailed. - hindmost

1 answer 1

At first glance, your code is working. Check what you get in formData, sometimes there is a cant.

Everything works for me like this:

 <form name="MyForm" enctype="multipart/form-data" type="POST"> <input type="file" name="myfile"> <button type="submit">Upload</button> </form> 

In the event handler, submit the submit form (alerts for sticking for clarity):

 var formData = new FormData($("form[name=MyForm]")[0]); $.ajax({ url: "url", type: "POST", data: formData, dataType: "json", cache: false, processData: false, contentType: false, success: function( respond, textStatus, jqXHR ){ if( typeof respond.error === "undefined" ){ alert( "Файл загружен успешно" ); } else{ alert( "ОШИБКИ ОТВЕТА сервера: " + respond.error ); } }, error: function( jqXHR, textStatus, errorThrown ){ alert("ОШИБКИ AJAX запроса: " + textStatus ); } });