Gabriel Santos
Gabriel Santos

Reputation: 4974

jQuery serialize() always empty

I can't get this script working. Every time I send a file the script need to do one ajax request and send to server the file, but, serialize always send empty string.

My Javascript

$('#upload-button input:file').change(function() {
    $('#upload-text').text('Sending file...');

    $.ajax({
        type: "GET",
        url: "?url=images/send",
        data: $('#image-upload').serialize(),

        success: function(response) {
            if(response.error) {
                $('#upload-text').text(response.error);
            } else if(response.success) {
                $('#upload-text').text('Image send');
            }
        },
    });
})

My HTML

<form name="image-upload" id="image-upload" action="?url=imagens/enviar" method="post" enctype="multipart/form-data">
    <input type="file" name="selected-image" id="upload-hidden" value="" />
</form>

When I have selected a file, result from alert($('#image-upload').serialize());:

// EMPTY //

Result from alert($('#image-upload input:file').attr('value')):

ponte-vecchio.jpg

Upvotes: 1

Views: 1054

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318518

Use the jQuery form plugin. It supports HTML5 file uploads and can fallback to a hidden iframe if the browser is too old.

Upvotes: 1

Tobias Krogh
Tobias Krogh

Reputation: 3932

checkout this fiddle. it sets up the basic html and JS via jQuery to use upload via iframe. a nice way to upload files "asynchronously" ;)

Upvotes: 1

Andreas
Andreas

Reputation: 21881

If you want to submit the file then you will have to go with an iframe-"workaround" described here, e.g.

For your problem, why serialize is always empty have a look at the source of jquery. The type of an input field is tested against this regex

 /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i

As you can see the type "file" isn't part of that and so jquery won't serialize this sort of input field.

Upvotes: 2

Related Questions