0

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.

dshin
  • 37
  • 6
  • 1
    The java script is not being called. The form is being submitted as form. Not sure what you are trying to do. – Jason K Nov 24 '20 at 22:29
  • @JasonK Are you sure? In the JS code there's an `init` method which defines an `onsubmit` event. `init` is fired on window load. – El_Vanja Nov 24 '20 at 22:49
  • @El_Vanja there's nothing there preventing the default submit action from continuing. – Phil Nov 24 '20 at 23:04
  • @JasonK hello, I believe the javascript is executed as I am able to print the results from the document elements. – dshin Nov 24 '20 at 23:23

1 Answers1

1

A couple things you are doing wrong here. You are sending a url-encoded POST request AND a XHR request when you click submit. The url-encoded POST is coming from action="process.php" in the input tag. Since the form post also causes a page reload the XHR gets terminated prematurely. You should remove that action and also add event.preventDefault() to your addEmployee call.

Open the network panel in the dev tools of your browser and you will see both requests.

  • Typically, a browser navigation event (the default form submit) will cancel XHR requests – Phil Nov 24 '20 at 23:06
  • @louisubchbinder Hello, thank you for your response. I added in the code you suggested and removed the action and method in the HTML tag, but unfortunately the new information from the PHP is not displayed. I can see the results in the dev tools preview, but the webpage itself is not updated. – dshin Nov 24 '20 at 23:21
  • @Phil Does this suggestion fix the cancellation? – dshin Nov 24 '20 at 23:23
  • @dshin you have no `onreadystatechange` or `onload` handler for your XHR request so of course you won't see anything happen. I suggest you look up some tutorials – Phil Nov 24 '20 at 23:24
  • @Phil Okay, I will try implementing, thank you – dshin Nov 24 '20 at 23:24
  • 1
    Yea thank you for jumping in @Phil. I think your first comment puts it a bit more eloquently than I said. \@dishin the reason you see the result in the first case is because you are triggering a page reload where the contents of that page are rendered from the various echo statements in your php script. Once you remove the page reload you no longer see the result because your js code does not handle it. – louisbuchbinder Nov 24 '20 at 23:31
  • @louisbuchbinder Oh, thank you for the clarification! – dshin Nov 25 '20 at 23:31