-1
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();

    var a = document.getElementById("name").value;
    var b = document.getElementById("message").value;
    var postdata = "name=a&message=b"; //Probably need the escape method for values here, like you did

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "/chat/backend-input.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(postdata);
}
</script>

<form onsubmit="loadDoc()">
Name: <input type="text" name="name" id="name"><br>
Message: <input type="text" name="message"><br>
<input type="submit"></input>
</form>

Why does this code not work? Have I done something wrong, when I press the submit button it does not POST the data from the form

Can someone explain where I have gone wrong?

Edit: Instead of outputting what is in the form it's outputting a and b.

jhop
  • 11
  • 2

1 Answers1

1

Firtly, don't forget to add the id="message" to the line: Message: <input type="text" name="message" id="message"><br>.

Posting data

You do

var postdata = "name=a&message=b";
// ...
xhttp.send(postdata);

So the values you are posting are effectively "a" and "b".

Instead of that, you need to add the values of the a and b variables to postdata. Simple string concatenation would do, but before you need to escape them (using encodeURIComponent()) in case they have special chars.

So, try the following to fix it. Change:

var postdata = "name=a&message=b";

To:

var postdata = "name=" + encodeURIComponent(a) + "&message=" + encodeURIComponent(b);

And it should work.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304