javascript - PHP Post and and print to innerHTML -
i trying post employee sql , display employee data after submit has button. can post , display not both @ same time. way should jsbin: https://jsbin.com/nenupupifo/edit?html,js,output
when implement php code post employee database refreshes form , not display output information. there better way this?
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 employeeid variable , store randomly generated 8 digit employee id number. make sure id number unique. var employeeid = parseint(math.random() * 100000000); // reference output goes: var output = document.getelementbyid('output'); // 3) add employeeid property employee object , set value employeeid variable. // 4) make employee object json object , send end json object. var employee = { firstname: firstname, lastname: lastname, department: department, employeeid: employeeid, date: new date() }; // 5) add each newly created employee employees array (check duplicate before adding). employees.push(employee); // 6) can debug things easier, use console.log output employees array console after creating new employee. console.log(employees); // 7) display emplodyee in 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 1 last line message display total number of employees have been added array. 'number of employees: ' + employees.length; // display 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 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;
Comments
Post a Comment