I know ajax is easy to use with jquery, but here I am trying to understand ajax with core javascript, I am sending two values name and age from index.html to indexPhp.php, In console it shows this message XHR finished loading: POST "http://localhost:8080/delPro/indexPhp.php".
but it is not showing any result in div, here is html, js and php script
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="scripts.js"></script>
</head>
<body>
Name: <input type="text" id="name" name="name"><br><br>
Age: <input type="text" id="age" name="age"><br><br>
<button type="submit" value="Submit" onclick="showUser()">Submit</button>
<div id="resultDiv"></div>
</body>
</html>
Javascript
function showUser() {
var hr = new XMLHttpRequest();
var url= "indexPhp.php";
var name= document.getElementById("name").value;
var age= document.getElementById("age").value;
var vars = {Name: name, Age: age};
hr.open("POST",url,true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
alert(hr.responseText);
document.getElementById("resultDiv").innerHTML = return_data;
}
}
hr.send(vars);
}
php script
if(isset($_POST['name']) && isset($_POST['age'])){
echo $name = $_POST['name'] . " " . $age = $_POST['age'];
}