Ciprian
Ciprian

Reputation: 3226

jQuery - FormData sends an empty image

Weird thing is happening when I submit a form using jquery. Even though I don't pick any image in the form, the $_FILES array contains an empty value. If I pick images, there is one extra empty value.

Has anybody seen this before?

Array
(
    [item_image] => Array
        (
            [name] => Array
                (
                    [0] => 
                )

            [type] => Array
                (
                    [0] => 
                )

            [tmp_name] => Array
                (
                    [0] => 
                )

            [error] => Array
                (
                    [0] => 4
                )

            [size] => Array
                (
                    [0] => 0
                )

        )

)

AJAX

$( "#fileupload" ).submit(function( event )
    {
        //disable the default form submission
        event.preventDefault();

        //grab all form data
        var formData = new FormData(this);

        $.ajax({
            url: 'ajax/add-item.php',
            data: formData,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data);
                if(data)
                {
                    $("#fileupload > div.alert").text('Upload successful.');
                    $('html, body').animate({scrollTop : 0},700);
                    document.getElementById("#fileupload").reset();
                }
            }
        });

    });

Upvotes: 1

Views: 1453

Answers (1)

angelcool.net
angelcool.net

Reputation: 2546

Try following this example:

Html/PHP

<?
    print_r($_POST);
    print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

jQuery

$("form#data").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

Good luck!!

Upvotes: 1

Related Questions