I am trying to create a file upload feature for my account management page. I would like to be able to upload a file without submitting the form. I am using a server-side upload script with CodeIgniter. Every time I run my script, the file input field is empty. How do I send the form data of one specific input to my ajax file?
<img src=".../attachments/f8725841986a40061b0f4da9f7ee45dd.png" width="100" height="100" border="0" alt="Avatar Not Available" src="..." id="avatar_response"/>
<input type="file" name="avatar" size="30"><a href="javascript:void(0);" rel="submitFile" data-input-name="avatar">Save</a>
$(document).on('click', '[rel="submitFile"]', function(){
console.log('anchor clicked');
var $anchor = $(this);
var input_name = $anchor.data('input-name');
var file_input = $('#'+input_name+'_file');
console.log(file_input);
var postdata = new FormData();
var files = file_input.files;
console.log(files);
postdata.append(input_name, files[0]);
$.ajax({
type: "POST",
url: "http://basecommand/index.php/ajax/upload/avatar/"+input_name,
dataType: "xml",
contentType: false,
processData: false,
statusCode: {
404: function(){
console.log("The file was not found.");
}
},
error: function(jqXHR, textStatus){
console.log("AJAX Error: "+textStatus);
},
success: function(xml)
{
console.log("ajax successful");
$(xml).find("upload").each(function(){
var fileurl = $(this).find("fileurl").text();
var response = $(this).find("response").text();
console.log(fileurl);
console.log(response);
})
}
});
});