I'm trying to get information from a form on HTML using Javascript, convert it to a JSON string and then send it to a PHP server to post, however, I'm running into the issue of receiving the data.
When the return value in the function addEmployee() is false, the PHP can grab the information but does not update the page. Whereas if the return value is set to true, it would update the page, but is unable to get the data from client, I need it for it to both so I am confused. I also tried implementing AJAX code, but it didn't seem to work.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Assignment 7</title>
<link rel="stylesheet" href="style.css" type=text/css>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="theForm" action="process.php" method="post">
<fieldset>
<legend>Add an Employee</legend>
<label for="firstName">First Name</label>
<br>
<input id="firstName" name="firstname" type="text">
<br>
<label for="lastName">Last Name</label>
<br>
<input id="lastName" name="lastname" type="text">
<br>
<label for="department">Department</label>
<br>
<select id="department" name="department" id="department">
<option value="Engineering">Engineering</option>
</select>
<br><br>
<input id="submit" type="submit">
</fieldset>
</form>
</body>
</html>
JavaScript Code:
var employees = [];
function generateID() {
return Math.random().toString().slice(2, 10);
}
function addEmployee() {
'use strict';
var fname = document.getElementById("firstName").value;
var lname = document.getElementById("lastName").value;
var dep = document.getElementById("department").value;
var id = generateID();
for(var i=0; i<employees.length-1; i++){
if(employees[i].id === id) {
id = generateID();
i = 0;
}
}
var employee = {
id:id,
fname:fname,
lname:lname,
dep:dep,
count:employees.length+1
};
employees.push(employee);
var JSONstring = JSON.stringify(employee);
const xhr = new XMLHttpRequest();
xhr.open("POST", "process.php");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSONstring);
return true;
}
function init() {
'use strict';
document.getElementById("theForm").onsubmit = addEmployee;
}
window.addEventListener("load", init);
PHP Code:
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<?php
$request = file_get_contents("php://input");
$arr = json_decode($request, true);
$browser = get_browser(null, true);
echo nl2br("Employee Added \r\n");
echo nl2br("Name: " . $arr["lname"] . ", " . $arr["fname"] ."\r\n");
echo nl2br("Department: " . $arr["dep"] ."\r\n");
echo nl2br("Employee ID: " . $arr["id"] ."\r\n");
echo nl2br("Hire Date: " . date("D M j Y") ."\r\n");
echo nl2br("Total Employees: " . $arr["count"] ."\r\n");
echo nl2br($browser["browser"] ."\r\n");
?>
</body>
</html>
I understand that I can grab the information directly from PHP but sending a JSON to the server is one of my assignment's requirements so I do not have a choice. Please help me.