gpt4 book ai didi

javascript - 我无法将 FormData 发送到 php

转载 作者:行者123 更新时间:2023-11-30 20:33:53 25 4
gpt4 key购买 nike

我有一个表格可以收集有关学生的所有信息并能够上传文件。现在,我的问题是我正在使用 ajax 将此值发送到 PHP。但是我无法将 formData 发送到我的 php 脚本。我使用 inspect Element 但没有发现错误。

这是我的表格:

我使用 onclick 事件将输入值发送到我的 JS 文件。

<form class="needs-validation" id="studentAdmissionForm" enctype="multipart/form-data" onsubmit="return false;" novalidate>

<legend>Student's Information</legend>
<hr>

<div class="form-row">
<div class="col-md-12 mb-3">
<label for="lrn">Learner's Reference Number: *</label>
<input type="number" class="form-control" name="lrn" id="lrn" placeholder="LRN" maxlength="12" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" required>
<div class="invalid-tooltip">
Please provide your LRN!
</div>
</div>
</div>

<div class="form-row">
<div class="col-md-3 mb-3">
<label for="studentFname">First name: *</label>
<input type="text" class="form-control" name="studentFname" id="studentFname" placeholder="First name" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="studentLname">Last name: *</label>
<input type="text" class="form-control" name="studentLname" id="studentLname" placeholder="Last name" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="studentMname">Middle name: *</label>
<input type="text" class="form-control" name="studentMname" id="studentMname" placeholder="Middle name" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="studentSname">Suffix name:</label>
<input type="text" class="form-control" name="studentSname" id="studentSname" placeholder="eg. Jr" maxlength="64">
</div>
</div>

<div class="form-row">
<div class="col-md-4 mb-3">
<label for="gender">Gender: *</label>
<select class="custom-select" name="gender" id="gender" required>
<option value="">Select Gender</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div class="invalid-tooltip">Please select your gender!</div>
</div>
<div class="col-md-4 mb-3">
<label for="dob">Date of Birth: *</label>
<input type="date" class="form-control" name="dob" id="dob" required>
<div class="invalid-tooltip">
Specify your date of birth!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="citizenship">Citizenship:</label>
<input type="text" class="form-control" name="citizenship" id="citizenship" placeholder="Citizenship" maxlength="64">
</div>
</div>

<div class="form-row">
<div class="col-md-4 mb-3">
<label for="religion">Religion: *</label>
<input type="text" class="form-control" name="religion" id="religion" placeholder="Religion" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="ethnicity">Ethnic Group:</label>
<input type="text" class="form-control" name="ethnicity" id="ethnicity" placeholder="Ethnic Group" maxlength="64">
</div>
<div class="col-md-4 mb-3">
<label for="motherTongue">Mother Tongue:</label>
<input type="text" class="form-control" name="motherTongue" id="motherTongue" placeholder="Mother Tongue" maxlength="64">
</div>
</div>

<legend class="mt-5">Contact Details</legend>
<hr>

<div class="form-row">
<div class="col-md-4 mb-3">
<label for="houseNum">House No. / Unit No: *</label>
<input type="text" class="form-control" name="houseNum" id="houseNum" placeholder="#" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-8 mb-3">
<label for="street">Street: *</label>
<input type="text" class="form-control" name="street" id="street" placeholder="Street" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
</div>

<div class="form-row">
<div class="col-md-6 mb-3">
<label for="village">Subdivision / Village / Building:</label>
<input type="text" class="form-control" name="village" id="village" placeholder="Subd, Village or Building" maxlength="64">
</div>
<div class="col-md-6 mb-3">
<label for="brgy">Barangay: *</label>
<input type="text" class="form-control" name="brgy" id="brgy" placeholder="Barangay" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
</div>

<div class="form-row">
<div class="col-md-4 mb-3">
<label for="city">City / Municipality: *</label>
<input type="text" class="form-control" name="city" id="city" placeholder="City" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="province">Province: *</label>
<select class="custom-select" name="province" id="province" required>
<option value="Tawi Tawi">Tawi-Tawi</option>
<option value="Zambales">Zambales</option>
<option value="Zamboanga Del Norte">Zamboanga Del Norte</option>
<option value="Zamboanga Del Sur">Zamboanga Del Sur</option>
<option value="Zamboanga Sibugay">Zamboanga Sibugay</option>
</select>
<div class="invalid-tooltip">Specify your province!</div>
</div>
<div class="col-md-4 mb-3">
<label for="zip">Zip Code: *</label>
<input type="number" class="form-control" name="zip" id="zip" placeholder="xxxx" maxlength="4" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
</div>

<div class="form-row">
<div class="col-md-4 mb-3">
<label for="tel">Telephone No:</label>
<input type="number" class="form-control" name="tel" id="tel" placeholder="Telephone No." maxlength="7" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
</div>
<div class="col-md-4 mb-3">
<label for="mobile">Mobile No: *</label>
<input type="number" class="form-control" name="mobile" id="mobile" placeholder="09xxxxxxxxx" maxlength="12" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="email">Email address: *</label>
<input type="email" class="form-control" name="email" id="email" placeholder="example@domain.com" maxlength="64" required>
<div class="valid-tooltip">
Looks good!
</div>
</div>
</div>

<legend class="mt-5">Guardian's Information</legend>
<hr>

<div class="form-row">
<div class="col-md-6 mb-3">
<label for="fatherName">Father's Name:</label>
<input type="text" class="form-control" name="fatherName" id="fatherName" placeholder="Lastname, Firstname & Middle Initial" maxlength="64">
</div>
<div class="col-md-6 mb-3">
<label for="fatherNum">Contact No:</label>
<input type="number" class="form-control" name="fatherNum" id="fatherNum" placeholder="Contact No." maxlength="12" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
</div>
</div>

<div class="form-row">
<div class="col-md-6 mb-3">
<label for="motherName">Mother's Name:</label>
<input type="text" class="form-control" name="motherName" id="motherName" placeholder="Lastname, Firstname & Middle Initial" maxlength="64">
</div>
<div class="col-md-6 mb-3">
<label for="motherNum">Contact No:</label>
<input type="number" class="form-control" name="motherNum" id="motherNum" placeholder="Contact No." maxlength="12" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
</div>
</div>

<div class="form-row">
<div class="col-md-6 mb-3">
<label for="guardianName">Guardian's Name:</label>
<input type="text" class="form-control" name="guardianName" id="guardianName" placeholder="Lastname, Firstname & Middle Initial" maxlength="64">
</div>
<div class="col-md-6 mb-3">
<label for="guardianNum">Contact No:</label>
<input type="number" class="form-control" name="guardianNum" id="guardianNum" placeholder="Contact No." maxlength="12" oninput="javascript: if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
</div>
</div>

<legend class="mt-5">Upload File (Optional)</legend>
<hr>

<p class="mb-3">To ease up the registration and enrollment procedure, you may attach a copy of the admission requirements (e.g. Form137, Transcript of Records, PSA (formerly NSO) Issued Birth Certificate, etc.).</p>
<p class="lead">Attach Files (Maximum of 10MB and allowed formats are: .JPG, .PNG, .DOC, .DOCX, .ZIP, .RAR and .PDF)</p>

<div class="form-row">
<div class="col-md-6 mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="file" id="file">
<label class="custom-file-label" for="file">Choose file</label>
</div>
</div>
</div>

<button type="submit" class="btn btn-primary" name="admissionBtn" id="admissionBtn" onclick="submitStudentData()">Submit</button>
<span id="status"></span>

</form>

在我的 JS 文件中:

这是我将值和文件发送到我的 PHP 脚本的方式

function submitStudentData() {
var lrn = _("lrn").value;
var studentFname = _("studentFname").value;
var studentLname = _("studentLname").value;
var studentMname = _("studentMname").value;
var studentSname = _("studentSname").value;
var gender = _("gender").value;
var dob = _("dob").value;
var citizenship = _("citizenship").value;
var religion = _("religion").value;
var ethnicity = _("ethnicity").value;
var motherTongue = _("motherTongue").value;
var houseNum = _("houseNum").value;
var street = _("street").value;
var village = _("village").value;
var brgy = _("brgy").value;
var city = _("city").value;
var province = _("province").value;
var zip = _("zip").value;
var tel = _("tel").value;
var mobile = _("mobile").value;
var email = _("email").value;
var fatherName = _("fatherName").value;
var fatherNum = _("fatherNum").value;
var motherName = _("motherName").value;
var motherNum = _("motherNum").value;
var guardianName = _("guardianName").value;
var guardianNum = _("guardianNum").value;
var file = _("file").files[0];
var successStatus = _("successStatus");
var status = _("status");

var formData = new FormData();

formData.append("lrn", lrn);
formData.append("studentFname", studentFname);
formData.append("studentLname", studentLname);
formData.append("studentMname", studentMname);
formData.append("studentSname", studentSname);
formData.append("gender", gender);
formData.append("dob", dob);
formData.append("citizenship", citizenship);
formData.append("religion", religion);
formData.append("ethnicity", ethnicity);
formData.append("motherTongue", motherTongue);
formData.append("houseNum", houseNum);
formData.append("street", street);
formData.append("village", village);
formData.append("brgy", brgy);
formData.append("city", city);
formData.append("province", province);
formData.append("zip", zip);
formData.append("tel", tel);
formData.append("mobile", mobile);
formData.append("email", email);
formData.append("fatherName", fatherName);
formData.append("fatherNum", fatherNum);
formData.append("motherName", motherName);
formData.append("motherNum", motherNum);
formData.append("guardianName", guardianName);
formData.append("guardianNum", guardianNum);
formData.append("file", file);

if(lrn == "" || studentFname == "" || studentLname == "" || studentMname == "" || gender == "" || dob == "" || religion == "" ||
houseNum == "" || street == "" || brgy == "" || city == "" || province == "" || zip == "" || mobile == "" || email == "") {
status.innerHTML = "<p class='red statusMsg'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Please fill out all required fields!</p>";
} else {
_('admissionBtn').disabled = true;
status.innerHTML = "<p class='statusMsg'><i class='fa fa-circle-o-notch fa-spin' aria-hidden='true'></i> Please wait...</p>";

var ajax = ajaxObj("POST", "inc/admission.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != 'success') {
status.innerHTML = ajax.responseText;
_('admissionBtn').disabled = false;
} else {
window.scrollTo(0, 0);
$('#studentAdmissionForm')[0].reset();
successStatus.innerHTML = "<div class='alert alert-dismissible alert-success'><button type='button' class='close' data-dismiss='alert'>&times;</button><h4 class='alert-heading'>Success!</h4><p class='mb-0'>Your data has been sent successfully!</p></div>";
}
}
}
ajax.send(formData);
}
}

我使用 formData.append() 获取所有值并将其发送到我的 php 脚本。但是就是发不出去,不知道是什么问题。我使用 Inspect Element 但没有发生错误。

这是我的 Ajax 模块:

function ajaxObj(method, url) {
var x = new XMLHttpRequest();
x.open(method, url, true);
x.setRequestHeader("Content-type","multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));
return x;
}

function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}

这是我的 PHP 脚本:

<?php
if(isset($_POST['lrn']) && !empty($_POST['lrn'])) {
include 'dbconn.php';

$lrn = mysqli_real_escape_string($conn, $_POST['lrn']);
$studentFname = mysqli_real_escape_string($conn, $_POST['studentFname']);
$studentLname = mysqli_real_escape_string($conn, $_POST['studentLname']);
$studentMname = mysqli_real_escape_string($conn, $_POST['studentMname']);
$studentSname = mysqli_real_escape_string($conn, $_POST['studentSname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$citizenship = mysqli_real_escape_string($conn, $_POST['citizenship']);
$religion = mysqli_real_escape_string($conn, $_POST['religion']);
$ethnicity = mysqli_real_escape_string($conn, $_POST['ethnicity']);
$motherTongue = mysqli_real_escape_string($conn, $_POST['motherTongue']);
$houseNum = mysqli_real_escape_string($conn, $_POST['houseNum']);
$street = mysqli_real_escape_string($conn, $_POST['street']);
$village = mysqli_real_escape_string($conn, $_POST['village']);
$brgy = mysqli_real_escape_string($conn, $_POST['brgy']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$province = mysqli_real_escape_string($conn, $_POST['province']);
$tel = mysqli_real_escape_string($conn, $_POST['tel']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$fatherName = mysqli_real_escape_string($conn, $_POST['fatherName']);
$fatherNum = mysqli_real_escape_string($conn, $_POST['fatherNum']);
$motherName = mysqli_real_escape_string($conn, $_POST['motherName']);
$motherNum = mysqli_real_escape_string($conn, $_POST['motherNum']);
$guardianName = mysqli_real_escape_string($conn, $_POST['guardianName']);
$guardianNum = mysqli_real_escape_string($conn, $_POST['guardianNum']);
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];

// File upload validation
if(!empty($fileName)) {
$fileExtn = explode(".", $fileName);
$fileActualExtn = strtolower(end($fileExtn));

$allowedType = array('jpg', 'jpeg', 'png', 'doc', 'docx', 'zip', 'rar', 'pdf');
if(in_array($fileActualExtn, $allowedType)) {
if($fileError == 0) {
if($fileSize < 10000) {
$fileNewName = uniqid('', true).".".$fileActualExtn;
$fileDestination = "../uploads/".$fileNewName;
move_uploaded_file($fileTmpName, $fileDestination);
} else {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Please upload a file that is less than 10mb!</p>";
exit();
}
} else {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> There was an error uploading your file, please try again!</p>";
exit();
}
} else {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> This file type is not allowed to upload!</p>";
exit();
}
} else {
$fileNewName = "";
}

$sql = "SELECT lrn FROM students";
$result = mysqli_query($conn, $sql);
$resultCount = mysqli_num_rows($result);
if($resultCount > 0) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> LRN was already in the database!</p>";
exit();
}

// Date of Birth Validation
function isRealDate($dob) {
if(false === strtotime($dob)) {
return false;
}

list($year, $month, $day) = explode('-', $dob);
return checkdate($month, $day, $year);
}

if(isRealDate($dob) != true) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Date of Birth is invalid!</p>";
exit();
}

if(empty($lrn) || empty($studentFname) || empty($studentLname) || empty($studentMname) || empty($gender) || empty($dob) || empty($religion) || empty($houseNum) || empty($street) || empty($brgy) || empty($city) || empty($province) || empty($zip) || empty($mobile) || empty($email)) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Please fill out all required fields!</p>";
exit();
} elseif(empty($fatherName) && empty($motherName) && empty($guardianName)) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Provide atleast one of your guardian(s)!</p>";
exit();
} elseif(!is_numeric($lrn) || !is_numeric($tel) || !is_numeric($mobile) || !is_numeric($fatherNum) || !is_numeric($motherNum) || !is_numeric($guardianNum)) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Only numbers are allowed on this fields (LRN, Telephone No., Mobile No., Guardian's Contact No.)</p>";
exit();
} elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p class='statusMsg red'><i class='fa fa-exclamation-triangle' aria-hidden='true'></i> Your email address is incorrect or invalid!</p>";
exit();
} else {
// Get age
$age = date_diff(date_create($dob), date_create('now'))->y;

$studentFnameNew = ucwords(trim(preg_replace('!\s+!', ' ', $studentFname)));
$studentLnameNew = ucwords(trim(preg_replace('!\s+!', ' ', $studentLname)));
$studentMnameNew = ucwords(trim(preg_replace('!\s+!', ' ', $studentMname)));
$studentSnameNew = ucwords(trim(preg_replace('!\s+!', ' ', $studentSname)));
$citizenshipNew = ucwords(trim(preg_replace('!\s+!', ' ', $citizenship)));
$religionNew = ucwords(trim(preg_replace('!\s+!', ' ', $religion)));
$ethnicityNew = ucwords(trim(preg_replace('!\s+!', ' ', $ethnicity)));
$motherTongueNew = ucwords(trim(preg_replace('!\s+!', ' ', $motherTongue)));
$houseNumNew = ucwords(trim(preg_replace('!\s+!', ' ', $houseNum)));
$streetNew = ucwords(trim(preg_replace('!\s+!', ' ', $street)));
$villageNew = ucwords(trim(preg_replace('!\s+!', ' ', $village)));
$brgyNew = ucwords(trim(preg_replace('!\s+!', ' ', $brgy)));
$cityNew = ucwords(trim(preg_replace('!\s+!', ' ', $city)));
$fatherNameNew = ucwords(trim(preg_replace('!\s+!', ' ', $fatherName)));
$motherNameNew = ucwords(trim(preg_replace('!\s+!', ' ', $motherName)));
$guardianNameNew = ucwords(trim(preg_replace('!\s+!', ' ', $guardianName)));
$approvalStatus = 0;

$sql = "INSERT INTO `students`(`lrn`, `student_firstname`, `student_lastname`, `student_middlename`, `student_suffixname`, `gender`, `dob`, `age`, `citizenship`, `religion`, `ethnic_group`, `mother_tongue`, `house_num`, `street`, `village`, `barangay`, `city`, `province`, `zip`, `tel`, `mobile`, `email`, `father_name`, `father_num`, `mother_name`, `mother_num`, `guardian_name`, `guardian_num`, `file`, `approval_status`) VALUES ('$lrn', '$studentFnameNew', '$studentLnameNew', '$studentMnameNew', '$studentSnameNew', '$gender', '$dob', '$age', '$citizenshipNew', '$religionNew', '$ethnicityNew', '$motherTongueNew', '$houseNumNew', '$streetNew', '$villageNew', '$brgyNew', '$cityNew', '$province', '$zip', '$tel', '$mobile', '$email', '$fatherNameNew', '$fatherNum', '$motherNameNew', '$motherNum', '$guardianNameNew', '$guardianNum', '$fileNewName', '$approvalStatus')";
$result = mysqli_query($conn, $sql);
echo "success";
}
}

最佳答案

不要使用这个:

x.setRequestHeader("Content-type","multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));

XMLHttpRequest 在表单元素之间使用自己的边界,它不会匹配您的随机边界。如果您省略它,则会自动发送正确的 header 。

关于javascript - 我无法将 FormData 发送到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com