1

I have an issue with my AJAX formData object. If select a file in the input and I send this with AJAX the array is empty. I hope somebody can help me with this. Below my code

HTML and JavaScript

    <form method="post" id="quoteform">
        <input type="file" name="uploadfile" id="quote"/>
        <input type="submit" value="upload"/>
    </form>
    <script type="text/javascript">
    document.getElementById("quoteform").addEventListener("submit", function(){
        var files           = document.getElementById("quote").files;
        var formData        = new FormData();
        
        for (var i = 0; i < files.length; i++) {
            var file = files[i]
            formData.append('files[]', file);
        }


        var xhttp           = new XMLHttpRequest();
        xhttp.open("POST", "linktophpfile.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send('upload='+formData);
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                alert(this.responseText);
            }
        }
        event.preventDefault();
    });
    </script>

PHP

<?php
if(isset($_POST['upload'])){
    print_r($_FILES);
}
?>

The PHP file returns Array ( )

1
  • when youre dealing with files it should be multipart/form-data Commented Aug 29, 2020 at 21:15

1 Answer 1

2
  1. when you upload files then you can't use application/x-www-form-urlencoded you have to use multipart/form-data

  2. you shouldn't mix strings with formData send('upload='+formData) it will only result in you uploading a string equal to upload=[Object object]

you should instead just send the formData and let the XHR or Fetch handle the content-type for you automatically.

  1. If you want an array then i presume you also want the attribute mulitple? You could always add in the required and accept="image/*, .txt" for good measure

  2. You don't manually have to add in all files to a formdata if you just use the first constructor argument that accepts a form element, everything from the form will be added

<form method="POST" action="https://httpbin.org/post" id="quoteform" encoding="multipart/form-data">
  <input multiple type="file" name="files[]" id="quote" required />
  <input type="submit" value="upload"/>
</form>
<script>
// html (xml) should mark the settings, behavior as it mostly always have done
// in all years way back and the js should provide enhancement and
// be more generally written to enhance the site (if js where
// to be turned off - most unlikely, I for once have it disabled in my phone)
// static sites works better without ads + annoying cookie popups
// it's a good thing Brave have quick toggle to enable scrips for js-only pages

function ajaxify (evt) {
  evt.preventDefault()
  var form = evt.target
  var formData = new FormData(form)

  fetch(form.action, {
    method: form.method,
    body: formData
  }).then(res => res.text()).then(alert)
}

document.getElementById("quoteform").addEventListener("submit", ajaxify)
</script>

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.