Question

I am having difficulty appending extra information to a formData object so It can be used in PHP to add to an SQL database. Unfortunately It relies on AJAX so to test you will need to run it on a server or localhost, but I have included a simple PHP file that will need to be called 'StackedTest.php'

I have been following the example on MDN but after a lot of time spent searching for the answer I am getting no where.

MDN formData object

thanks for any help.

<html>

<head>

    <script type="text/javascript">
        var returned;
        var fd;

        function ajaxCall(sends){

            fd = new FormData();
            var images = document.getElementById('images');

            fd.append('file', images.files[0]);


            /**
             **
             ** This doesn't seem to be working, I am trying to append the value of the select box ** to the FILES array
             ** so I can use it in php to add to an SQL database.
             **
             **/

            fd.append('catagory', document.getElementById('cat').value);

                var ajax=new XMLHttpRequest();
                ajax.onreadystatechange=function(){
                if (ajax.readyState==4 && ajax.status==200){
                    document.getElementById("response").innerHTML = ajax.response;
                    fd = null;
                    }
                }
                ajax.open("POST","Stackedtest.php",true);
                ajax.send(fd);
            }


    </script>   

</head> 

<body>

<div id="content">

    <div>
        <form method="post" enctype="multipart/form-data" action="?">
            <select name="cat" id="cat"><br>
                <option value="opt1">option 1</option>
                <option value="opt2">option 2</option>
                <option value="opt3">option 3</option>
            </select><br>
            <input type="file" name="images[]" id="images" multiple /><br>  
            <button type="button" id="btn" onclick="ajaxCall()">Upload Files!</button>  
        </form>

        <p id="response">Response text here</p>

    </div>  

</div> <!-- END CONTENT -->

</body>

</html>

PHP Script

<?php 

if(isset($_FILES['file'])){
    print_r($_FILES['file']);
    print_r($_FILES['catagory']);
}

?>
Was it helpful?

Solution

category is sent as post data so access it using the post super global $_POST

<?php 

if(isset($_FILES['file'])){
    print_r($_FILES['file']);
    print_r($_POST['catagory']);
}

?>

EDIT: the files super global is also sent via post but is only for items that are uploaded to the PHP script

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top