.ajax上传文件并发送文本输入到php,显示错误信息但上传成功
问题描述:
我知道这是一个简单的问题,专家在这里,但它一直困扰着我几天。我是一名初学者,我认为在处理数据方面存在一些问题。.ajax上传文件并发送文本输入到php,显示错误信息但上传成功
所以我这里的目的是把用户上传的文件和电子邮件都发送到upload.php,然后upload.php会返回一个引用ID,然后显示给用户。
我面临的问题是警告我与基准数的,相反,它会显示两个错误:
- 未定义指数fileToUpload在XAMPP/htdocs中...
- 有一个在上传文件时错误
但是,上传文件是成功的,我可以看到在我的databas上传的文件e和参考代码已成功生成。
如果这两个问题都解决了,我怎样才能在HTML部分显示参考代码。谢谢!!!任何帮助感谢!
<form id="main-contact-form" class="main-contact-form" name="main-contact-form" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Address">
<input type="file" name="fileToUpload" id="fileToUpload" value="fileToUpload">
<input type="submit" value="submit" name="submit" class="btn btn-primary pull-left crsa-selected">
</div>
</form>
这里是我的阿贾克斯调用,将要发送的电子邮件地址,并上传文件upload.php的
$(document).ready(function() {
$("#main-contact-form").on('submit',(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
success: function()
{
alert("ajax success");
}
});
function reqListener() {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = function() {
alert(this.responseText);
};
oReq.open("get", "upload.php", true);
oReq.send();
}));
});
这是我upload.php的
<?php
include("db.php");
$target_dir = "";
$target_file = "";
$target_dir = "submittedform/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$refId = "";
// upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded. <br/>";
$refID = !empty($_POST['refID']) ? $_POST['refID'] : time() . rand(10*45, 100*98);;
// echo "Reference ID: " . $refID . "<br/>";
echo json_encode("Reference ID: " . $refID . "<br/>");
#once file uploaded, the path and reference code will be updated, status will be set to 1
$sqlInsert = "INSERT INTO student(reference_id, upload_appli_form, status) VALUES ('$refID', '$target_file', '1')";
$qInsert = mysqli_query($db, $sqlInsert) or die("Error : ". mysqli_error($qInsert));
}
else
{
echo json_encode("Sorry, there was an error uploading your file. <br/>");
}
mysqli_close($db);
?>
答
也许它必须是简单?喜欢这个?
现在它是异步的。所以这将是有效的多年:D
$(document).ready(function() {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function(result) {
alert(result); //your POST answer
});
}));
});
什么是错误? –
'async:false' is deprecated and will called error – ixpl0
and why you do'var oReq = new XMLHttpRequest();'如果您已经使用了'.ajax();'? – ixpl0