0

It's working but on every submit I receive an array even tho a file is not even added to the file input (multifile input)

    postData = new FormData(this); 
    $.ajax({
        url: "/url",
        type: "POST",
        data: postData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data, textStatus, jqXHR) {
            if (data === "true") {
                window.location.replace("/url");
            } else {
                $(".errors").html(data);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            swal("Der opstod en fejl");
        }
    });

What i get from $_FILES is the following

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

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

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

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

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

Is there a way where I can avoid this from happening?

6
  • Yes, validate that you have had a file added to the array before allowing the upload. Commented Jan 27, 2016 at 18:27
  • Please add the context so we can see from where you get this. Commented Jan 27, 2016 at 18:27
  • That's standard behavior for a file upload where no file was provided. note the error code 4 - UPLOAD_ERR_NO_FILE Commented Jan 27, 2016 at 18:27
  • @MarcB Issue tho is even tho i add a file it will keep having the last array with the error 4 is that normal ? Commented Jan 27, 2016 at 18:42
  • you'd have to show how you set up your html form. given the array format and you say it's a multi-upload, you could very easily have two separate file inputs and are only filling in one. Commented Jan 27, 2016 at 18:44

1 Answer 1

1

Try adding required attribute to input type="file" element to prevent submission of form if no files selected by user

$("form").on("submit", function(e) {
  e.preventDefault();
  // do `$.ajax()` stuff
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form>
  <input type="file" name="files[]" multiple required />
  <input type="submit" />
</form>

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

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.