user3574670
user3574670

Reputation: 19

if and else does not compare inside XMLHttpRequest()

function banUser() {
  var userToBan = document.getElementById('userToBan').value;
  var cid = document.getElementById('chatId').value;

  if (userToBan.length <= 0) {
    var x = document.getElementById("banerror");
    x.innerHTML = "\tEnter the Username of the user you wish to ban!";
    return;
  }

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var returncode = this.responseText;
      if (returncode == "0") {
        var x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " successfully banned!";
        document.getElementById('userToBan').value = "";
      } else if (returncode == "1") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tMissing Variables";
      } else if (returncode == "2") {
        x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " does not exist!";
      } else if (returncode == "3") {
        window.location.href = "main.php";
      } else if (returncode == "4") {
        x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " is already banned!";
      } else if (returncode == "5") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tAn admin cannot be banned!";
      } else if (returncode == "6") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tCreator can not be banned!";
      } else if (returncode == "7") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tYou must be an Admin or creator to ban a user!";
      }
    }
  }

  xhr.open("POST", "processBanUser.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send("chatId=" + cid + "&userToBan=" + userToBan);
}

for some reason the javascript inside the if and else does not print out the value.. please help.. i tried to code with out the if else then it work... but when i put the if else statement in... the javascript stop working.

Upvotes: 0

Views: 28

Answers (1)

Pragun
Pragun

Reputation: 1241

Add console.log(returncode); at line 20. The returncode values aren't string but you're comparing if they're a string. Hence the error in logic. Or you can simple remove the quotes in your if...else condition like

if ( returncode == 0 ){ }
else if (returncode == 1) {}

Upvotes: 1

Related Questions