Skip to content Skip to sidebar Skip to footer

Php Upload Auto Submit After Browse A File

I want to make a simple site that would let you browse for an mp3 and upload it automatically. here is my code

Solution 1:

Maybe use something like this:

<input type="file" name="mp3" onchange="this.form.submit();" />

Although I don't condone inline event handlers, it's just an example to make sure it works for you. The point is to catch the onchange event of the file input and then submit its form. Instead of using this.form or whatever, you can grab the form by ID (after giving it one) and call submit() on it.

UPDATE:

To keep your existing PHP code working, give your submit button an id attribute (something other than "submit") and try using this:

<input type="file" name="mp3" onchange="document.getElementById('submit_button_id').click();" />

Again, this could be more maintainable/readable if you made it a function call, like:

<input type="file" name="mp3" onchange="submitForm();" />
<input type="submit" name="submit" id="submit_button_id" value="Upload" />

<script type="text/javascript">
    function submitForm() {
        // However you need to submit the form

        document.getElementById("submit_button_id").click(); // Or whatever
    }
</script>

If you would rather change the PHP, you can use the original this.form.submit(); (or just use .submit() on the form element in whatever way). In the PHP, what you really care for is to check if $_FILES['mp3'] is set, so it's up to you if you need to check for the submit button's presence. I forget exactly how isset() works, so I don't want to assume and tell you something wrong. You might be able to use other logic, but the real thing you care about is if the file was sent in the submission, even though it might make it "better" if you make sure a button was used to submit it (though not necessary).


Solution 2:

Simple, attach a onchange() JS event to it.

<input type="file" name="mp3" onchange="call .submit() on a form"/><br />

This will submit the form when the user chooses a file. It's safer and more efficient to create these handlers in Jquery or a separate JS script. But for this example, it doesn't matter.

For more information, view this question: HTML <input type='file'> File Selection Event


Post a Comment for "Php Upload Auto Submit After Browse A File"