简体   繁体   中英

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?

<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
            $('#fileToUpload').on('change', function() {
            var myFormData = new FormData();
            var file = document.getElementById('fileToUpload').value;
            var gid = document.getElementById('gid').value;
            var user = document.getElementById('user').value;
            myFormData.append('file', file);
            myFormData.append('gid', gid);
            myFormData.append('user', user);
            });

            $.ajax({
                url: 'imgupload.php',
                type: 'POST',
                processData: false, // important
                contentType: false, // important
                dataType : 'json',
                data: myFormData
            });

            </script>

On imgupload.php I get the POST data like this

$gid = $_POST['gid'];
$user = $_POST['user'];

It worked when I used the HTML form method. What's wrong here?

FormData.append() takes key-value pairs, so this is wrong:

myFormData.append(file,gid,user);

You need something like:

myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);

Appart from that you need to put this code inside an event handler so that it triggers when you need it to.

For example:

$('#fileToUpload').on('change', function() {
  // your javascript code
});

And you should probably also put it inside a document.ready block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM