javascript - Retrieving a value from a dropdown menu using PHP

Solution:

The issue is the way you are sending form data to PHP. Better way of doing is to use new FormData() function of Javascript. It sends the serialized data so no additional processing is needed.

const hours = document.getElementById("hours");

for (let i = 1; i <= 12; i++) {
  hours.innerHTML += `<option value="${i}">${i}</option>`;
}

const minutes = document.getElementById("minutes");

for (let i = 0; i <= 45; i += 15) {
  if (i < 10) {
    minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
  } else {
    minutes.innerHTML += `<option value="${i}">${i}</option>`;
  }
}

function ajaxSubmit() {
  var form = document.querySelector('form');
  var data = Object.fromEntries(new FormData(form));
  console.log(data)
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.status == 200 && xhr.readyState == 4) {
      document.querySelector("#isSent").innerHTML = xhr.responseText;
    }
  }

  xhr.open('POST', 'mail.php?', true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(data);
}
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
  <h5>Schedule your 15 minute consultation</h5>
  <p id="date">MM/DD/YYYY</p>
  <div id="time">
    <select id="hours" name="hour"></select> <span>:</span>
    <select id="minutes" name="minute"></select>
    &nbsp;
    <div id="timeLabel">
      <label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
    </div>
  </div>

  <input placeholder="Name" name="name" id="name" />
  <input placeholder="Email" name="email" id="email" />

  <button class="submitBtn" name="submitBtn">SUBMIT</button>

  <p id="isSent"></p>
</form>

Answer

Solution:

Change your $_POST from hour to plural hours, the same with minute to minutes.

    $hours = null;
    $minute = null;

    if(isset($_POST['hours'])) {
        $hours = $_POST['hours'];
    }

    if(isset($_POST['minutes'])) {
        $minutes = $_POST['minutes'];
    }
    
    //this message will display on #isSent paragraph
    if(isset($hours) and isset($minutes))
        echo "your Schedule 15 minute consultation($hours:$minutes) has been registered!";

Tip: for javascript generating readable time format use padStart function:

for(let i = 0; i <= 45; i+=15) {
    minutes.innerHTML += `<option value="${(''+i).padStart(2,'0')}">${(''+i).padStart(2,'0')}</option>`;
}

Insead of if else statement condition.

for(let i = 0; i <= 45; i+=15) {
  if(i < 10) {
    minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
  } else {
    minutes.innerHTML += `<option value="${i}">${i}</option>`;
  }  
}

Source