-3

I am trying to make a simple JavaScript game, and as a user, I will get a score. I want to send this score to a PHP server, but in my case, I can't get this data in the PHP file.

Here my JavaScript code:

var obj = {
  "note": 0,
};
obj.note = score;
console.log(obj.note)
var data, xml, txt = "", mydata;
data = JSON.stringify(obj.note);
xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
  if (this.readystate == 4 && this.status == 200) {
    mydata = JSON.parse(this.responseText);
    for (x in mydata) {
      txt += mydata[x];
    }
    // document.getElementsByClassName("pEl").innerHTML = txt;
  }
};
xml.open("POST", "getnote.php", true);
console.log("true");
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send("x=" + data);

Here my PHP code:

<?php
  // Takes raw data from the request
  $json = file_get_contents('application/x-www-form-urlencoded');

  // Converts it into a PHP object
  $data = json_decode($json);
  echo $data
?>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132

1 Answers1

0

Many people tried to help you, you used a valid sample which you linked, anyway still using the wrong code, which you modified with no reason and all you had to do was to follow suggestions from GeeksForGeeks page you linked.

Short You can not use anything you want when you trying to access php://input stream (you used application/x-www-form-urlencoded, which is wrong, and I have no even idea why?)

Working, minified sample

test.html

<script>
    let obj = {
        "note": 123,
        "foo": "bar"
    };
    let data, xml;
    data = JSON.stringify(obj);
    xml = new XMLHttpRequest();
    xml.open("POST", "getnote.php", true);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.send(data);
</script>

getnote.php

<?php
// Takes raw data from the request
$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json, true);

// print whole array decoded from JSON object
print_r($data);

// print single node of the array
echo "The sent note is: {$data['note']}";
echo "The sent foo is: {$data['foo']}";
// etc.

Please, read once again the article you linked, also read carefully the question linked by El Vanja to recognize what mistake you did.

Note: that should be just a comment, and probably will be flagged to delete, anyway I have no idea what else we can do if you don't want to read the simple comments that solve your problem and give you a detailed description.

biesior
  • 55,576
  • 10
  • 125
  • 182