1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I see, guess it's back to the drawing board then, thanks for the input, Giorgio.
there are ways of uploading files asynchronously though, search for "ajax file upload" eg. with some customization you could simulate normal form submit behavior with file upload
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.