'I'm trying to learn the basic of ajax. I want to send a form data using post method to the server and get back a response text that's all
I know how to use the GET method but is hard to understand the POST method with a form.
I'm sure there is something wrong with the line request.send(); but I'm sorry I couldn't get it.
Also what If there is more than one field like I want to send name + email
My HTML code
<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo 2</title>
</head>
<body>
<form action="demo2.php" method="post">
Email: <input type="email" name="email" required >
</form>
<button onclick="loadContent()">Load</button>
<div id="ServerContent">
<p></p>
</div>
<script>
function loadContent(email){
//Create request object
let request = new XMLHttpRequest();
let email = document.getElementsByName("eamil").values;
//Create event handler that specifies what should happen when server responds
request.onload = function(){
//Check HTTP status code
if(request.status == 200){
//Get data from server
let responseData = request.responseText;
//Add data to page
document.getElementById("ServerContent").innerHTML = responseData;
}
else
alert("Error communicating with server");
}
//Set up request with HTTP method and URL
request.open("POST", "demo2.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//Send request
request.send();
}
</script>
</body>
</html>
My PHP code
<?php
//Get email string - need to filter input to reduce chances of SQL injection etc.
$emailString = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_URL);
if($emailString != ""){//email string exists
echo 'Hello ' . $emailString;//Output message with contents of query string
}
else{//Query string parameter 'email' cannot be found
echo 'Hello stranger';
}
Solution 1:[1]
var url = "url to your php file";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}};
var data = `{
"email": "youremailvariable",
"name": "yournamevariable"
}`;
xhr.send(data);
Try this way
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | qMartis |
