I try to send POST data from html form to PHP script by using Ajax (XML httprequest ) with vanilla JavaScript then retrieve that data and display it to a specific html element.
the problem is when i click the button to submit the form , seems that the code in Ajax part does not send data to php script and at the same does not retrieve data to the specific html element.
//here is my php script I named it data.php
<?php
error_reporting(~E_NOTICE);
if( $_POST["name"]) {
echo "Welcome ". $_POST['name']. "<br />";
exit();
}
?>
//and here is my html , JavaScript and ajax
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>demo</title>
<style>
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="card">
<div class="card-body">
<form method="post" name="myForm" onsubmit="return validateForm();" action="data.php">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control" name="name" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter name">
</div>
<p class="text-center text-danger" id="loader">Load and display the value of name here with ajax</p>
<button type="submit" onclick="loadDoc()" class="btn btn-primary">Submit</button>
</form>
<script>
function validateForm(){
let validation = {
name:document.myForm.name.value
};
let msg = new Array("Name required");
if(validation.name == null || validation.name == ""){
alert(msg);
return false;
}
function loadDoc(){
xhttp = new XMLHttpRequest();
xhttp.open('POST','data.php',false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(validation.name);
document.getElementById("loader").innerHTML = xhttp.responseText;
}
}
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>