ShoeLace1291 ShoeLace1291 - 2 years ago 80
Javascript Question

How do I post form data without submitting the form with jQuery?

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 = $'input-name');
var file_input = $('#'+input_name+'_file');

var postdata = new FormData();

var files = file_input.files;

postdata.append(input_name, files[0]);

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");
var fileurl = $(this).find("fileurl").text();
var response = $(this).find("response").text();


Answer Source

Try this:

var postdata = new FormData();
if (formId == "imageForm") {
    var filesList = document.getElementById('imgFile');
    for (var i = 0; i < filesList.files.length; i++) {
        postdata.append('file', filesList.files[i]);

You can add other parameters like this:

formdata = $("#" + formId + "").serialize() + "&ProductId=" + productId + "&Sku=" + sku + "&IsVideo=" + isVideo;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download