4

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?

9
  • what do you see in the console ? any errors .visit network tab Commented Mar 31, 2016 at 6:22
  • where is myFormData()? Commented Mar 31, 2016 at 6:22
  • you need enctype="multipart/form-data" this in form to upload files Commented Mar 31, 2016 at 6:27
  • @SantoshRamKunjir, to do this I have to use the <form> HTML tag right? Commented Mar 31, 2016 at 23:10
  • 1
    You're not actually pulling the values out of your input elements, you're just getting the html elements themselves. Commented Apr 1, 2016 at 6:14

1 Answer 1

1

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.

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

3 Comments

I made the changes you said, but still nothing. I updated the code on the question
@YohanBlake If you missed it, see my comment below your question.
@HeadCode There is definitely plenty wrong here :-)

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.