I'm aware that this is possible using JQuery's ajax functions but I'm specifically wanting to try do this using JQuery's .load()
function.
Here's my code:
HTML:
<form class="form" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="csv-file">
<p class="upload-button">Upload</p>
<p class="upload-output"></p>
</form>
Javascript:
$('.upload-button').click(function() {
var formData = $('.form').serializeArray();
$('.upload-output').load('upload.php', formData);
});
When I click on the upload-button
the form is serialized and sent to my PHP file called upload.php
. This is the contents of upload.php
- I'm currently just checking to see if it recieves the file at all:
if(isset($_FILES['csv-file'])){
echo 'found file';
} else echo 'no file';
All of this looks fine but for some reason it returns no file
every time and I'm not sure why.
I've tried different input types like a text
field, textarea
and they all work but whenever I try to pass an input with type file
it doesn't work. Why is this? and how can I get the file through to my PHP file using .load()
? Is it even possible?
Actually, you can't upload files with Ajax that way because .serialize() only gives you the file names.
Use FormData:
$('.upload-button').click(function() {
var formData = new FormData($('form')[0]);
$('.upload-output').load('upload.php', formData); });
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.