1

I have two function which should each send either 0 or 1 on a php page with ajax. when pressing a key on the keyboard, the function that sends 1 starts and the one that sends 0 must start three seconds later with a setTimeout (). The problem is that the second function doesn't send. I send you the party of the corresponding code. Thanking you in advance for your help, and please forgive my not very nice English to read ^^'

My code :

function typing() {
  var typingBool = 1
  if (typingBool != "") {
    let donneee = {}
    donneee["typingBool"] = typingBool
    let donneeeJson = JSON.stringify(donneee)
    let xmlhttp = new XMLHttpRequest()
    xmlhttp.open("POST", "ajax/typing.php")
    xmlhttp.send(donneeeJson)
  }
}

function typing2() {
  var typingBool = 0
  if (typingBool != "") {
    let donneee = {}
    donneee["typingBool"] = typingBool
    let donneeeJson = JSON.stringify(donneee)
    let xmlhttp = new XMLHttpRequest()
    xmlhttp.open("POST", "ajax/typing.php")
    xmlhttp.send(donneeeJson)
  }
}

var typingText = document.getElementById('texte');
typingText.addEventListener('keypress', function() {
  typing();
  setTimeout(function() {
    typing2()
  }, 3000);
})
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • your typing2 func doesnt make much sense, whats the purpose of the typingBool var and the if? – EugenSunic Dec 18 '20 at 16:34
  • `0 != ""` <-- this returns `false`, because `0` is falsy, and `""` is falsy, so your `if` does not pass. Use `!==` to perform a strict check. But yes, your code seems a little verbose, it could be shortened quite a bit – blex Dec 18 '20 at 16:36
  • What's the point of doing `if` immediately after assigning the variable? – Barmar Dec 18 '20 at 16:41

1 Answers1

0

The main problem here is the difference between != & !==:

if (0 !=  "") { console.log("Won't be displayed"); }
if (0 !== "") { console.log("Will be displayed");  }

That being said, your code could be shortened a bit, this should work:

function typing(typingBool){
  let donneeeJson = JSON.stringify({ typingBool: typingBool });
  let xmlhttp = new XMLHttpRequest();
     
  xmlhttp.open("POST", "ajax/typing.php");
  xmlhttp.send(donneeeJson);
}

var typingText = document.getElementById('texte');
typingText.addEventListener('keypress', function(){
  typing(1);
  setTimeout(function(){ typing(0); }, 3000);
});
blex
  • 24,941
  • 5
  • 39
  • 72