File Upload Javascript + php

Asked

Viewed 470 times

0

Hello, I need to send some files via post to handle in PHP. However, I want to post via Javascript, passing other parameters in Ubmit and be able to handle in PHP. The way I’m doing, I don’t get any $_FILE, only works the $_FILE in php when I just pass it as parameter in the post, without the other parameters.

$(document).ready(function (e) {
            $('#upload').on('click', function () {
                var file_data = $('#file').prop('files')[0];
                var form_data = new FormData();
                form_data.append('file', file_data);

                $.post({
                    url: 'upload.php', // point to server-side PHP script 
                    dataType: 'text', // what to expect back from the PHP script
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: {action: 'enviar', form: form_data}, //quero passar assim, mais de um parametro, o form_data seria o file. 
                    type: 'post',
                    success: function (response) {
                        $('#msg').html(response); // display success response from the PHP script
                    },
                    error: function (response) {
                        $('#msg').html(response); // display error response from the PHP script
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>Single File Upload Example using PHP</h1>
    <p id="msg"></p>
    <input type="file" id="file" name="file" />
    <button id="upload">Upload</button>
</body>

And in php I can’t return $_FILE, because this way I don’t recognize it, unless I just pass date: form_data. But I need to pass the other parameters together.

  • And why not include the value of action on its own form_data?

  • already tried to recover so $_POST['form'] ?

  • yes, adding the form_data worked, thank you.

1 answer

0


You can send the value of action: 'enviar' by the object itself FormData that you own, just do:

var form_data = new FormData();

form_data.append('file', file_data);
form_data.set('action', 'enviar');

And to send, you can put only data: form_data, the same way it worked.

This will generate the HTTP request field in the body action with the value 'enviar' and in PHP you can do $_POST['action'] normally.

  • So it worked, thanks. ( I don’t think I can vote because my user is new)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.