0

So I have this function and I want the program to wait for it to return a value instead of giving undefined.

function savedNumberOfLessonInDay(dayID){
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
            return this.responseText;
        }
      };
      var PageToSendTo = "AJAX/countLessonInDay.php?";
    var MyVariable = dayID;
    var VariablePlaceholder = "GETDayID=";
    var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
      xhttp.open("GET", UrlToSend, false);
      xhttp.send();
   }
<?php

require '../notWebsite/dbh.php';
session_start();
$dayID = (int)$_GET['GETDayID'];

$sqlCount = "SELECT COUNT(lessonID) FROM daylesson WHERE dayID = ?";
  $stmt = mysqli_stmt_init($conn);

  if(!mysqli_stmt_prepare($stmt, $sqlCount)) {
   header("Location: ../GymnasieArbeteHemsida.php?error=countError");
    exit();
  }
  else {
 mysqli_stmt_bind_param($stmt, "i", $dayID);//Puts in variable in question
   mysqli_stmt_execute($stmt);//Executes the question
mysqli_stmt_bind_result($stmt, $result);//Binds the reuslt of the question to the variable $result
if(mysqli_stmt_fetch($stmt)){//If the result of the question can be recieved
  echo $result;//Send the result to the website
}


        exit();
  }

  mysqli_stmt_close($stmt);
  mysqli_close($conn);



 ?>
  document.getElementById('demo').innerHTML = 'test' + savedNumberOfLessonInDay(number);

This code returns testundefined to demo but 16(which is the number I'm after) to demo4. How do I make it returns test16 to demo instead of testundefined?

MrCookie
  • 5
  • 3

3 Answers3

0

You can't call savedNumberOfLessonInDay(number) to get the number. You are trying to do so using return this.responseText;, but that won't trigger until the request to the server has finished.

You might use Promises to solve this.

function savedNumberOfLessonInDay(dayID){
     return new Promise((resolve) => {
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
            resolve(this.responseText);
        }
      };
      var PageToSendTo = "AJAX/countLessonInDay.php?";
    var MyVariable = dayID;
    var VariablePlaceholder = "GETDayID=";
    var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
      xhttp.open("GET", UrlToSend, false);
      xhttp.send();
     });
   }

And use await to call it:

  document.getElementById('demo').innerHTML = 'test' + await savedNumberOfLessonInDay(number);

Or, if for some reason you can't use await:

  savedNumberOfLessonInDay(number).then((response) => {
      document.getElementById('demo').innerHTML = 'test' + response;
  });
Jorjon
  • 5,316
  • 1
  • 41
  • 58
0

The function savedNumberOfLessonInDay() will not wait for the ajax to complete. So you need to set the html for demo within the callback function xhttp.onreadystatechange.

Without changing you're implementation too much, you can simply modify your code:

function savedNumberOfLessonInDay(dayID){
 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
        document.getElementById('demo').innerHTML = 'test' + this.responseText;
    }
  };
  var PageToSendTo = "AJAX/countLessonInDay.php?";
var MyVariable = dayID;
var VariablePlaceholder = "GETDayID=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
  xhttp.open("GET", UrlToSend, false);
  xhttp.send();

}

And Then just call the function instead of trying to set the

savedNumberOfLessonInDay(number);
JordinB
  • 306
  • 1
  • 2
  • 13
0

try using async/await here is how to use it. https://javascript.info/async-await

Zinah NA
  • 46
  • 3