Hey im trying to get rid of jquery and go pure javascript.
The problem is when do the ajax request no data is coming back from the request
Here is process. I am not getting any data in the processing part.
<form name="inputform" method="post">
<input type="text" id="user" name="user">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="button" value="submit" onclick="myFunction()">
</form>
<script>
function myFunction()
{
var data = new FormData();
//apend name first then variable
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
data.append('user', email);
data.append('name', name);
data.append('email', email);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test-process.php', true);
xhr.onload = function () {
// do something to response... show data in alert
//console.log(this.responseText)
alert(this.responseText);
};
xhr.send(data);
}
</script>
test-process.php
<?php
$user = $_POST["user"];
$name = $_POST["name"];
$email = $_POST["email"];
echo $user;
echo $name;
?>
>Solution :
There seem to be a couple of issues in your code. One issue is that you are using the variable email to append to the FormData object, but the email variable is not defined. Instead, you should be using the email input element to get its value and append it to the FormData object.
Another issue is that you are trying to access the form data in the PHP script using $_POST, but you are not checking whether the request method is POST before accessing the data. To do this, you can use the $_SERVER[‘REQUEST_METHOD’] variable to check the request method.
Here’s an updated version of your code that should fix these issues:
<form name="inputform" method="post">
<input type="text" id="user" name="user">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="button" value="submit" onclick="myFunction()">
</form>
<script>
function myFunction() {
var data = new FormData();
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
data.append('user', user);
data.append('name', name);
data.append('email', email);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test-process.php', true);
xhr.onload = function () {
// do something to response... show data in alert
alert(this.responseText);
};
xhr.send(data);
}
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = $_POST["user"];
$name = $_POST["name"];
$email = $_POST["email"];
echo $user;
echo $name;
}
?>