1

the idea is basically to be able to write your age in a form, and after your age is submitted some content is goign to be loaded. (for example, relevant music that someone in your age might like). before I start working on that i want to see if i can just echo the submitted age. and i am having a problem doing this with xhttp requests.

i tried changing between GET and POST methods, I tried switching the form attribute so instead of "action" i give it a "onsubmit". the solutions i tried so far either did nothing, or it showed a php "undefined index" error. another problem I got was that the error showed up for a second and then disappeared.

step 1 - index.php:

<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="javascript:loadLiving();">Living</a>
    </li>
  </ul>
</nav>

<div id="body">    </div>

step 2 - scripts:

function loadLiving() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("body").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "living.php", true);
  xhttp.send();
}

step 3 - living.php:

    <div class="list-group">
      <a href="#houseform" class="list-group-item" data-toggle="collapse">Buying a house</a>
      <div id="houseform" class="collapse">
          <form action="javascript: calculateHousing();" method="POST">
          <br>
          <input type="text" name="age" placeholder="What is your Age"/>
          <button name="submit" type="submit">SUBMIT</button>
          </form>
          <br>
      </div>


step 4 - scripts.js:

function calculateHousing() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("body").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "getHousing.php", true);
  xhttp.send();
}

from getHousing.php:

<?php

if(isset($_POST['submit'])) {
echo $_POST["age"];
}
  ?>

expected to see the age echo'd in the "body" div. but i get a blank, the form and the collapsable disappears but nothing is loaded.

j a
  • 51
  • 7
  • 2
    In short, you're successfully making the AJAX requests but not sending the values in those requests. The linked duplicate contains a variety of examples to help. – David Feb 11 '19 at 19:04

0 Answers0