John Smith John Smith - 2 months ago 6
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() {
xhr.open("GET", "welcome.php");
xhr.send("your_name=john&your_age=40");

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'];
var_dump($user);


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?

Answer

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

xhr.open("GET", "welcome.php?your_name=john&your_age=40");
Comments