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?
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.