我正在尝试将员工发布到sql并在提交按钮后显示员工数据。我可以让它发布和显示但不能同时发布。 这是它应该看的方式 JSBin:https://jsbin.com/nenupupifo/edit?html,js,output
当我实现php代码时,它将员工发布到数据库,但随后刷新表单并且不显示输出信息。有一个更好的方法吗?
var employees=[];
function process() {
'use strict';
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var department = document.getElementById('department').value;
// 2) Create an employeeId variable and store a randomly generated 8 digit employee id number. Make sure the id number is unique.
var employeeId = parseInt(Math.random() * 100000000);
// Reference to where the output goes:
var output = document.getElementById('output');
// 3) Add an employeeId property to your employee object and set its value to your employeeId variable.
// 4) Make the employee object as a JSON object and send it to the back end as a JSON object.
var employee = {
firstName: firstName,
lastName: lastName,
department: department,
employeeId: employeeId,
date: new Date()
};
// 5) Add each newly created employee to your employees array (check duplicate before adding).
employees.push(employee);
// 6) Just so you can debug things easier, use console.log to output your employees array to the console after creating a new employee.
console.log(employees);
// 7) Display the emplodyee in the output HTML.
var message = '<h2>Employee Added</h2>Name: ' + employee.lastName + ', ' + employee.firstName + '<br>';
message += 'Department: ' + employee.department + '<br>' + 'Employee ID: ' + employee.employeeId + '<br>' + 'Hire Date: ' + employee.date.toDateString() + '<br>' +
// 8) Add one last line to your message that will display the total number of employees that have been added to your array.
'Number of employees: ' + employees.length;
// Display the employee object:
output.innerHTML = message;
addtosql2(employee)
return false;
}
function addtosql2(employee) {
<?php $servername = "localhost"; ?>
<?php $username = "root"; ?>
<?php $password = ""; ?>
<?php $dbname = "employees"; ?>
<?php $conn = mysqli_connect($servername, $username, $password, $dbname); ?>
<?php if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$firstName = employee.firstName;
$lastName = employee.lastName;
$department = employee.department;
$id = employee.id;
$sql = "INSERT INTO employee (firstname, lastname, department, id ,dateAdded)
VALUES ('$firstName', '$lastName', '$department', '$id', NOW())";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn); ?>
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
}
window.onload = init;