JustaN00b
JustaN00b

Reputation: 317

jquery ajax upload form serialize

I'm having some difficulties with uploading an image from an html form. The form is added to a div when someone clicks on an item, here's the code for that:

$("#editavatar").click(function(){
    $(".rightdisplay").html('<form class="upload" method="post" enctype="multipart/form-data">');
    $(".rightdisplay").append('<div class="editavatar"></div>');
    $(".rightdisplay .editavatar").append('<div class="boxtitle">edit avatar</div>');
    $(".rightdisplay .editavatar").append('<div class="boxwrapm"><input type="file" name="imageup" id="imageup" value="" /></div>');
    $(".rightdisplay .editavatar").append('<div class="boxwrapm"><input type="submit" name="submit" class="imageupload" value="Send" /></div>');
    $(".rightdisplay .editavatar").append('</form>');
    Cufon.replace('.boxtitle');
});

The form is created properly, the problem is that when I try to serialize the form when someone clicks the submission button is that the dataString variable stays empty:

$(document).on("click", "input.imageupload", function(event){
    event.preventDefault();
    dataString = $("form.upload").serialize();
    alert(dataString);
    $.ajax({
        type: "POST",
        url: "http://xxx/upload.php",
        data: dataString,
        dataType: "json",
        success: function(json){
            if(json.jresponse==true){
                $(".avatar").css({"background" : "url(http://xxx/images/avatars/"+json.juser+".png) #000000 center center no-repeat;"});
            }
            alert(json.jmessage);
        },
        error: function(xhr, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
    return false;
});

Why doesn't it serialize?

Upvotes: 1

Views: 10308

Answers (2)

Anand Mishra
Anand Mishra

Reputation: 430

If you want to upload files with form data need to include following js file:

<script src="http://malsup.github.com/jquery.form.js"></script>

And use the following code on any event:

var options = { 
  url: url,
data : {'username' : username, 'password' :     password ,'repeatpassword' :repeatpassword,'firstname' :firstname,'lastname' :lastname,'email' :email},
success:function(data) { 
    alert(data);    
  } 
}; 

$('#formId').ajaxForm(options);

Upvotes: 0

giorgio
giorgio

Reputation: 10202

ajax cannot upload files and jquery does not serialize file input fields, see also http://api.jquery.com/serialize/

Upvotes: 3

Related Questions