[英]Image upload via ajax POST without using HTML form
I am trying to send some data via POST method to a PHP file without using form in HTML. 我试图通过POST方法将一些数据发送到PHP文件而不使用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 在imgupload.php
我得到了这样的POST数据
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. 当我使用HTML表单方法时,它工作。 What's wrong here? 这有什么不对?
FormData.append()
takes key-value pairs, so this is wrong: FormData.append()
接受键值对,所以这是错误的:
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. 你应该把它放在document.ready块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.