potatoguy
potatoguy

Reputation: 5

Why is my AJAX request not returning the correct text?

I have a HTML file and a PHP file.

The HTML file has 3 clickable div buttons. When I click each of them, they should trigger a different Javascript function that returns different AJAX response.

My problem is that no matter which button I click, the program always produces the same AJAX response from only one function.

Specifically, no matter which button I click, the program always sends out a GET request from the showAll() function. I know this because I make the PHP file print out the GET request parameter and it always says the "show" parameter equals to "all", when I want the parameter to equal to "major" or "course".

HTML

<div id="List">
      <div id="entries">
  </div>

  <a href="" onclick="showAll()">
      <div id="button_all" class="buttons">
          <p> Show All</p>
      </div>
  </a>

    <input id="major" type="text">

  <a href="" onclick="filterM()">
        <div class="buttons">
            <p>Filter by Major</p>
        </div>
  </a>

      <input id="course" type="text">

  <a href="" onclick="filterC()">
    <div class="buttons">
            <p>Filter by Course</p>
        </div>
  </a>

</div>

<script>

  function showAll(){
    var xmlhttp;
    if(window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var mesgs = document.getElementById("entries");
        mesgs.innerHTML = xmlhttp.responseText;
        document.getElementById("button_all").style.display = "none";
      }
    }
    xmlhttp.open("GET","queryEntries.php?show=all", true);
    xmlhttp.send();
  }

  function filterM() {
    var xmlhttp;
    var majorName = document.getElementById("major").value;
    alert("filterM() has been clicked and majorName is " + majorName);
    if(window.XMLHttprequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var mesgs = document.getElementById("entries");
        mesgs.innerHTML = xmlhttp.responseText;
        document.getElementById("button_all").style.display = "block";
      }
    }
    xmlhttp.open("GET", "queryEntries.php?show=major&value=" + majorName, true);
    xmlhttp.send();
  }

function filterC() {
  alert("filterC() had been clicked");
  var xmlhttp;
  var courseName = document.getElementById("course");
  if(window.XMLHttprequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      var mesgs = document.getElementById("entries");
      mesgs.innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET", "queryEntries.php?show=course&value=" + courseName, true);
  xmlhttp.send();
  document.getElementById("button_all").style.display = "block";
}

    </script>
   </body>
</html>

PHP

<?php

$db_server = "...";
$db_user = "...";
$db_pwd = "...";

// Create connection
$conn = mysqli_connect($db_server, $db_user, $db_pwd) or die('Connection failed! ' . mysqli_error($conn));

// Select database
mysqli_select_db($conn, "h3517511") or die("Selection failed! " . mysqli_error($conn));

// Construct SQL query
echo "The show is: " . $_GET['show'] . "<br>";
echo "The value is: " . $_GET['value'];
$query = 'SELECT * FROM attendanceList';

if ($_GET['show'] == "major") {
    echo "MAJOR";
    $query = 'SELECT * FROM attendanceList WHERE major = "'.$_GET['value'].'" ';
}

if ($_GET['show'] == "course") {
    echo "COURSE";
    $query = 'SELECT * FROM attendanceList WHERE course = '.$_GET['value'].' ';
}

// Execute SQL query
$result = mysqli_query($conn, $query) or die('Query execution failed! ' . mysqli_error($conn));

while($row = mysqli_fetch_array($result)){
    print "<div id=".$row['id'].">";
    print "<span>".$row['attendOrNot']."</span>";
    print "<h3>".$row['studentname']." (".$row['major'].")</h3>";
    print "<h5>(".$row['course'].") on ".$row['coursedate']." </h5>";
    print "</div>";
}

    ?>

Upvotes: 1

Views: 86

Answers (2)

Amr Berag
Amr Berag

Reputation: 1108

Make sure the IF statment is valid in your php code. Try it like this:

if (trim($_GET['show']) === "major")

Define xmlhttp using var keyword. the way you are defining it is making it global so it will always have the values of the first request after refreshing the page.

Solution 1:
Chang this :

xmlhttp = new XMLHttpRequest();

to this :

var xmlhttp = new XMLHttpRequest();

Solution 2:

Use different name for it in each js function like xmlhttp1, xmlhttp2 and xmlhttp3
..........................
I recommend to use both solutions together at the same time because the query word from the input field may change so in this case solution 2 alone is not enough.

Upvotes: 0

Aberel
Aberel

Reputation: 162

Try the following code, it's based on yours but uses only one JS function with variables, which is easy to control and debug.

This is the main code:

<div id="List">
    <div id="entries"></div>

    <input id="all" type="hidden" value="all">
    <a onclick="submitFilters('all', 'none')">
        <div id="button_all" class="buttons">
            <p>Show All</p>
        </div>
    </a>

    <input id="major" type="text">
    <a onclick="submitFilters('major', 'block')">
        <div class="buttons">
            <p>Filter by Major</p>
        </div>
    </a>

    <input id="course" type="text">
    <a onclick="submitFilters('course', 'block')">
        <div class="buttons">
            <p>Filter by Course</p>
        </div>
    </a>
</div>

<script>

function submitFilters(name, buttonDisplay){
    var xmlhttp;
    var value = document.getElementById(name).value;
    alert(name + " has been clicked and value is " + value);

    if(window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var mesgs = document.getElementById("entries");
        mesgs.innerHTML = xmlhttp.responseText;
        document.getElementById("button_all").style.display = buttonDisplay;
      }
    }
    xmlhttp.open("GET", "queryEntries.php?show=" + name + "&value=" + value, true);
    xmlhttp.send();
}

</script>

EDIT:

I cleaned the "href" attributes, which are not needed when use "onclick". If you want the classic link style, add this block to your HTML:

<style>
a {
    text-decoration: underline;
    cursor: pointer;
    color: blue;
}
</style>

Upvotes: 1

Related Questions