Js, PHP WITH AJAX: how to determine the letter grade of students using javascript with ajax?

so I made a program about an exam and I need to determine the letter grades of students but first they have to answers some questions then base on what score the student gets the student will get a letter grade, someone recommended me to use AJAX because i need to do the process itself in the form without refreshing so I tried to make it but I ended up getting confused can someone help me please.

this are the codes:

    <div class = "form">
<button id = "submit" name = "submit"  value = "submit" > SUBMIT </button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <h3> Are you sure you want to submit? </h3>
    <button id = "yes" name = "yes" class = "yes" value = "submit" onclick ="loadDoc()"> YES </button>
    <button id = "no" name = "no" class = "no"> NO </button>
  </div>
</div>


<div id="myModalLast" class="modalLast">
  <div class="modal-contentLast">
   <a href = "personal.php"> <span class="close">&times;</span> </a>

<div class = "pic">
    <img src="Logo.png" width = "150" height = "150">
</div>  
    <h3> Full name: Cathleen Joyce Imperial Almeda </h3>  
    <h3> Total items:20 <p id = "score" name = "scorename"></p> </h3>  
   <h1> <br><p id = "scores" name = "realscores"></p>

   Rank:<p id = "rank"></p>
</h1> 

  </div>
</div>
</div>

this is for the ajax part:

    <script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("score").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("post", "examExtension.php", true);
  xhttp.send();
}
</script>

and this for examExtension.php

    <?php


$score = isset($_POST['score']) ? $_POST['score'] : '';


if ($score > 19 and $score < 21){
echo "A+";
}
if($score  > 18 and $score< 20){
echo "A";
}
if($score  > 17 and $score< 19){
echo "A-";
}
if($score  > 16 and $score< 18){
echo "B+";
}
if($score  > 15 and $score < 17){
echo "B";
}
if($score  > 14 and $score< 16){
echo "B-";
}
if($score  > 13 and $score< 15){
echo "C+";
}
if($score  > 12 and $score < 14){
echo "C";
}
if($score  > 11 and $score< 13){
echo "C-";
}
if($score  > 10 and $score< 12){
echo "D+";
}
if($score  > 9 and $score< 11){
echo "D";
}

?>

and lastly this is for the counting of scores it is based on how many radio buttons the student correctly clicked.

     <script>document.getElementById("yes").addEventListener("click", function() {
  let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length;
  document.getElementById("score").innerHTML = "Your Score: " + numberOfCorrectAnswers;


});


</script>

thanks in advance for the help

So where are you getting confused?

I will say that this can be simplified:

if ($score > 19 and $score < 21){ 
echo "A+";
}
if($score  > 18 and $score< 20){
echo "A";
}
if($score  > 17 and $score< 19){
echo "A-";
}
if($score  > 16 and $score< 18){
echo "B+";
}
if($score  > 15 and $score < 17){
echo "B";
}
if($score  > 14 and $score< 16){
echo "B-";
}
if($score  > 13 and $score< 15){
echo "C+";
}
if($score  > 12 and $score < 14){
echo "C";
}
if($score  > 11 and $score< 13){
echo "C-";
}
if($score  > 10 and $score< 12){
echo "D+";
}
if($score  > 9 and $score< 11){
echo "D";
}

All of those rules get you down to a single number, so why are you giving a range?

It’s not working that’s why I’m confused everytime I get the score the letter grades are not appearing

Open yourbrowser tools and see what it is doing.
From there you can see what you are sending to your script, which doesn’t appear to be anything at all, and what it returns back.

Failed to load resource: the server responded with a status of 404 (Not Found) that appeared

but it’s for the photo

Network tab. It will show what goes out and what comes in.

Like I said initially, I don’t see you sending anything to the script. Test this by modifying it like this

 <?php
print_r($_POST);

$score = isset($_POST['score']) ? $_POST['score'] : '';


if ($score > 19 and $score < 21){
echo "A+";
}
if($score  > 18 and $score< 20){
echo "A";
}
if($score  > 17 and $score< 19){
echo "A-";
}
if($score  > 16 and $score< 18){
echo "B+";
}
if($score  > 15 and $score < 17){
echo "B";
}
if($score  > 14 and $score< 16){
echo "B-";
}
if($score  > 13 and $score< 15){
echo "C+";
}
if($score  > 12 and $score < 14){
echo "C";
}
if($score  > 11 and $score< 13){
echo "C-";
}
if($score  > 10 and $score< 12){
echo "D+";
}
if($score  > 9 and $score< 11){
echo "D";
}

i see, the problem is in the examExtension.php it doesn’t appear in the network tab so it is ajax

Not exactly. The issue is you aren’t sending anything to the examExtension file for it to do anything in your ajax request.

ummm so what to do, I’m really confused I’m sorry

Did you add the code I told you to?

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

See what it shows you from this

yes i added it, ahhh okay so its send.

So I made a program about an exam and I need to determine the letter grades of students but first, they have to answers some questions then base on what score the student gets the student will get a letter grade, someone recommended me to use AJAX because I need to do the process itself in the form without refreshing so I tried to make it but I ended up getting confused can someone help me, please.

I’m confused because everytime I click the button the result is always no score has been given

Here are the codes:

 <div class = "form">
<button id = "submit" name = "submit"  value = "submit" > SUBMIT </button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <h3> Are you sure you want to submit? </h3>
    <button id = "yes" name = "yes" class = "yes" value = "submit" onclick ="loadDoc()"> YES </button>
    <button id = "no" name = "no" class = "no"> NO </button>
  </div>
</div>


<div id="myModalLast" class="modalLast">
  <div class="modal-contentLast">
   <a href = "personal.php"> <span class="close">&times;</span> </a>

<div class = "pic">
   
</div>  
    <h3> Full name: Cathleen Joyce Imperial Almeda </h3>  
    <h3> Total items:20 <p id = "score" name = "scorename"></p> </h3>  
   <h1> <br><p id = "scores" name = "realscores"></p>

   Rank:<p id = "rank"></p>
</h1> 

  </div>
</div>
</div>

this is for the ajax part:

  <script>

function loadDoc(score) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      scoreElement.innerHTML = "Your Score: " + this.responseText;
      console.log('Grade calculation complete');
    }
  };
  xhttp.open("post", "examExtension.php", true);


  xhttp.send('score=' + score);
}
</script>

And this for examExtension.php:

   <?php


if (!isset($_POST['score'])) {
  echo 'No score has been given';
  exit;
}



$score = intval($_POST['score']);

if ($score > 19 and $score < 21) {
  echo "A+";
} else if ($score > 18 and $score < 20) {
  echo "A";
} else if($score > 17 and $score < 19) {
  echo "A-";
} else if ($score > 16 and $score < 18) {
  echo "B+";
} else if ($score > 15 and $score < 17) {
  echo "B";
} else if ($score > 14 and $score < 16) {
  echo "B-";
} else if ($score > 13 and $score < 15) {
  echo "C+";
} else if ($score > 12 and $score < 14) {
  echo "C";
} else if ($score > 11 and $score < 13) {
  echo "C-";
} else if ($score > 10 and $score < 12) {
  echo "D+";
} else if($score  > 9 and $score < 11) {
  echo "D";
}

exit;

?>

And lastly, this is for the counting of scores it is based on how many radio buttons the student correctly clicked.

    <script>
const scoreElement = document.getElementById("score");
const yesButton = document.getElementById("yes");

yesButton.addEventListener("click", function() {
  let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length;


  loadDoc(numberOfCorrectAnswers);
  console.log('Calculating grade');
});
</script>
function ajaxRoutine() {
    var sendScore = 'score=' + score;

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
        if (xhr.readyState === 2) {
            //console.log(xhr.status);
            if (xhr.status === 410) {
                console.log(xhr.status);
            }
        }
        if (xhr.readyState === 4 && xhr.status === 200) {
            var scoreElement.textContent = "Your Score: " + JSON.parse(xhr.responseText);
            console.log(''Grade Calculation Complete",  scoreElement.textContent);
        }
    }; // End of Ready State:

    xhr.open('POST', "examExtension.php", true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send(sendScore);
}

PHP

<?php

/* Makes it so we don't have to decode the json coming from javascript */
header('Content-type: application/json');

$score = filter_input(INPUT_POST, 'score', FILTER_SANITIZE_NUMBER_INT);

if ($score > 19 and $score < 21) {
  output("A+");
} else if ($score > 18 and $score < 20) {
  output("A");
} else if($score > 17 and $score < 19) {
  output("A-");
} else if ($score > 16 and $score < 18) {
  output("B+");
} else if ($score > 15 and $score < 17) {
  output("B");
} else if ($score > 14 and $score < 16) {
  output("B-");
} else if ($score > 13 and $score < 15) {
  output("C+");
} else if ($score > 12 and $score < 14) {
  output("C");
} else if ($score > 11 and $score < 13) {
  output("C-");
} else if ($score > 10 and $score < 12) {
  output("D+");
} else if($score  > 9 and $score < 11) {
  output("D");
}

function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * If everything validates OK then send success message to Ajax / JavaScript
 */

function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

Not Sure if this will work as I haven’t tested out, but it should get you in the ballpark.

why did you create another topic for this?

sorry i tried to make it and I was succesful on sending but this time it’s another problem it’s not an error it’s just that the result is not the one that i want, it’s always "no score has been given " im sorry if i can’t reply earlier there was a time limit

The link I posted gives an example of a correct post the way you are attempting. Currently, you are missing the header that they have causing yours to not function as expected.

so i need to make a header does the link you sended have that?

Example: POST

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

so is it like this?

`function loadDoc(score) {
var xhttp = new XMLHttpRequest();

xhttp.open(“post”, “examExtension.php”, true);

xhttp.setRequestHeader(‘Content-type’, ‘application/x-www-form-urlencoded’);

xhttp.onreadystatechange = function() {
if (this.readyState == XMLHTTPRequest.done && this.status == 200) {
scoreElement.innerHTML = "Your Score: " + this.responseText;
console.log(‘Grade calculation complete’);
}
}

xhttp.send(score);
}
`

Sponsor our Newsletter | Privacy Policy | Terms of Service