I am trying to implement file upload functionality on my site.
I have created the actual PHP script for uploading and this is what I’ve added to my HTML:
<form enctype="multipart/form-data" action="PHPScripts/upload.php" method="POST">
<input type="file" id="browseButton" name="image" onchange="this.form.submit();" />
</form>
This triggers the upload.php as expected, however, this is not what I want to achieve exactly. I want to implement AJAX instead. So, when the user chooses the file, I want to trigger the JavaScript function and I want that function to call the upload.php subsequently.
But there’s a problem: How am I supposed to pass the POST parameters (i.e. $_POST["upload"] and $_FILES["image"]) to PHP function through the JavaScript? I know it’s supposed to be simple, but I’m stuck. Thanks for clarifying.
Update
Changelog explained that this is not possible in the way I imagined. My ultimate goal is to achieve the following:
- User browses for an image to upload.
- PHP uploads the image to the designated location on the server machine.
- (This is critical) The uploaded file is presented in a predefined tag after it has been successfully uploaded. Could you give some recommendations on how to achieve the third step? Thanks a bunch.
You won’t be able to do the file upload via AJAX.
Basically what an AJAX interception does is it serializes the values on your form (you can try
$('#form_id').serialize()on your console to see what it does).Because the file is read from the disk, you don’t have that data available at submit time and can’t do it via AJAX like you can with regular fields.