I'm having trouble with simple Ajax / JavaScript / PHP. I am using Ajax to call a PHP script that generates a random number.
I have managed successfully to call a script and to show that random number inside a element.
But the problem is, I need to use that number for later calculations and I don't know how to convert xhttp.responseText
to number and store it in a var.
All i get from .responseText
is either Nan
, either undefined
, or in this case <p id = "number">VALUE</p>
.
Can anyone help, please?
Here is the full code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id= "btn" type="button" onclick="loadDoc()">Generate number</button>
<div id="random">
<p id = "number"></p>
</div>
<script src = "javascript.js"></script>
</body>
</html>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("number").innerHTML =
xhttp.responseText;
}
};
xhttp.open("POST", "script.php", true);
xhttp.send();
console.log(number);
}
//PHP
<?php
function getRandom(){
$rand = rand(1,16);
return $rand;
}
echo getRandom();
?>
Change your php code to
<?php
function getRandom(){
$rand = rand(1,16);
return $rand;
}
echo getRandom();
?>
you are not returning anything from php. Add echo before getRandom() function
//New Edit
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id= "btn" type="button" onclick="loadDoc()">Generate number</button>
<div id="random">
<p id = "number"></p>
<input type='hidden' id="number_1" value='0' />
</div>
<script src = "javascript.js"></script>
</body>
</html>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("number").innerHTML = xhttp.responseText;
document.getElementById('number_1').value = xhttp.responseText; //This sets the value in hidden field and you can use it later.
alert(document.getElementById('number_1').value);
}
};
xhttp.open("POST", "script.php", true);
xhttp.send();
console.log(number);
}
</script>
to parse number from string, use js function parseInt(). and probably check your php returning anything
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.