Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Serialize a form for uploading images

    I'm having some difficulties with uploading a image from an html form.
    The form is added to a div when someone clicks on an item, here's the code for that:
    Code:
    $("#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:
    Code:
    $(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?

    Thanks in advance

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,472
    Thanks
    0
    Thanked 634 Times in 624 Posts
    You have a multi-part form - one part is a file and the other part is the rest of the form. Only the regular form fields can be serialized because only they contain text that can be serialized. You can't serialize a file using JavaScript because JavaScript has no access to the file part of the form.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •