Xhttp post javascript

Hi, I’m having a problem getting this code to work:

in html file:

var data = "its working";


function test() {

  var xhttp; 

  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

      document.getElementById("answer").innerHTML = this.responseText;

    }
  };

  xhttp.open("POST", "destination.php", true);
  xhttp.setRequestHeader("Content-type", "text/plain");
  xhttp.send(data);

}

in php file:

<?php 

$result = $_POST['data']; 


echo "hello world";
echo $result;

?> 

The output i get is only “hello world”, and not the $result variable.

any help is appreciated

thanks:)

1 Like

Hello, I’m new to php as well and here’s what I understand.

Since you set your as a text/plain, the request will not send the data as a query string. This means that you can’t use $_POST to refer to the data.

So, change this one:

xhttp.setRequestHeader("Content-type", "text/plain");

To this:

xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Though, that’s not enough. You want to send the data in the query string format.

It should look something like this:

"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

So using your example, if you want to send "it's working" and refer to it as data in your php’s $_POST, you can try changing your xhttp.send() to be similar to this:

xhttp.send("data=" + data);

// comment: expanded it will be ->  xhttp.send("data=it's working")

Hopefully that helps.

I learned all of this from this MDN article on AJAX page specifically step 1.

thanks a lot man, this really helped. Also thanks for the MDN article, explained a lot.

1 Like

No worries. I’m glad that my answer is helpful to you.