Search code examples
phpjavascriptajaxajax-request

Get Javascript variables to a PHP file using AJAX


I am a newbie in web base applications development and Im learning AJAX. Here is my problem, I'm trying to make an AJAX request with some variables (user inputs) and get the php file with the same variables. Below is my code, if there something I am missing or I am doing wrong please let me know, I will appreciated any help! Thank you.

Javascript code:

<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest;
try{
  ajaxRequest = new XMLHttpRequest();
 }catch (e){
   try{
     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
     }catch (e) {
  try{
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }catch (e){
    document.getElementById("Alert").innerHTML= "*Your browser broke!";
    document.getElementById("Alert").style.color = '#E00000 ';
     return false;
   }
  }
 }
  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('display');
      ajaxDisplay.value = ajaxRequest.responseText;
     }
   }
 var input_building = document.getElementById('building').value;
 var input_room = document.getElementById('room').value;
 var queryString = "?building=" + input_building + "&room=" + input_room;
 ajaxRequest.open("GET", "map.php" + queryString, true);
 ajaxRequest.send(); 
}
 </script>

HTML:

  <select id="building" name="building">
     <option value="#" default >Select</option>
     <option value="Luis C. Monzon">Luis C. Monzon</option>
  </select>
  <input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" >
  <input id="submit" type="button" value="submit" onclick="ajaxFunction()" >
  <p id="display"></p>

PHP file:

<?php>
  $building = $_GET['building'];
  $room = $_GET['room'];

  echo "<h1>".$room." ".$building."</h1>";
  ?>

Solution

  • You are setting a value property on a <p> element. You should be setting its innerHTML. Value is used for input fields.

    document.getElementById('display').innerHTML = ajaxRequest.responseText;