upload a file using jquery ajax function
Hello again,
I am trying to create a possibility for users to
1) select an image using an input field --> the image is displayed in a preview box by the function readURL --> that works fine
2) upload that image to process sever side wise by clicking a div calling a function uploadImage --> HERE IS THE PROBLEM
The html code:
- <input type="file" id="imgInput" />
- <div id="submitAddImage" class="messageBoxSubmitButton">Bild hinzufügen</div>
No <form> tag around used. Also functions are called on events --> both function give at least a response when I for examploe trouble shooting using alert();
- $( '#imgInput' ).change( readURL );
- $( 'div#submitAddImage' ).on( 'click' , uploadImage );
With the readURL function I am creating an object using FileReader mechanism. The file is then displayed in $( 'img#previewWindow' ).
- var myFile = '';
- function readURL( e ) {
if ( this.files && this.files[0] ) {
var reader = new FileReader();
reader.onload = ( function( e ) {
$( 'img#previewWindow' ).attr( 'src' , e.target.result );
});
reader.readAsDataURL( this.files[0] );
myFile = this.files[0]; // store file in global variable
}
}
Clicking the div-Button executes the upload funtion.
- function uploadImage() {
var data = new FormData();
$.each( myFile , function( key , value ) {
data.append( key , value );
});
$.ajax({
url: 'changeUploadImage.php',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function( data , textStatus , jqXHR )
{
if( typeof data.error === 'undefined' ) {
submitForm( event, data );
} else {
alert( 'ERRORS: ' + data.error );
}
},
error: function(jqXHR, textStatus, errorThrown) { alert( 'error on upload' ); }
});
- }
THE RESULT IS THAT I END UP WITH THE ALERT 'error on upload'. So the upload fails. I don't understand also after long trying how to create an object (don't know for example how to show me the object, what are to properties like path, type, image itself,...) and then to pass over to the ajax function to uplaod. I also do not understand, whether I need the each function for the maFile variable. I thought I have profund skills using jquery, but connot master this issue, which sucks!
So what is it exactly that creates me the object and how can I pass on to another function?
Can someone help? I am thinking already about trying other approached discarting the ajax upload function. But that would be even more frustrating...
Thank you in advance
Frank