John Smith John Smith - 4 months ago 10
Ajax Question

Why does this Ajax request not seem to pass the JS variable through to PHP?

I'm currently struggling to figure out how to pass variables from JS to PHP using Ajax. I have tried using the following Ajax code

xhr = new XMLHttpRequest();

function myFunction() {"GET", "welcome.php");

xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
document.getElementById("output").innerHTML = xhr.responseText;


Combined with a PHP script called welcome.php which looks as follows:

$user = $_GET['your_name'];

For some reason, however, this outputs 'NULL' and I can't work out why.

I've also tried including
echo $user;
in file welcome.php, but this doesn't return anything.

Anyone know why this is happening?


you are using method GET, as stated in .send documentation

If the request method is GET or HEAD, the argument is ignored and request body is set to null.

What you want to do is"GET", "welcome.php?your_name=john&your_age=40");