Reputation: 87
I am learning JavaScript without jQuery.
Right now I am trying to pass some data from an input field to php and than pass a $variable
from php to javascript. In jQuery this is easy with $.ajax
.
But how do I do this with ONLY JavaScript? Here is my attempt. Right now I only want to pass the $_POST
content from the inputfield
. I didn't do any validation at this moment.
My plan is to make a validation with php and then pass an error message or more than one. Or in case of success an success message.
But out of my console log I am only getting NULL
.
window.onload = function () {
var Input = document.querySelector('input#Input');
var InputButton = document.querySelector('button.formBtn');
InputButton.onclick = function () {
var InputRequest = new XMLHttpRequest();
InputRequest.open("POST", "ajax.php", true);
InputRequest.send();
InputRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(InputRequest.response)
console.log(obj);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Example</title>
<style>
#Input {
width: 200px;
height: 15px;
padding: 10px 0;
text-indent: 5px;
}
#Input:focus {
outline: none;
border: 1px solid lightblue;
}
</style>
</head>
<body>
<form name="form" action="ajax.php" method="post">
<input type="text" id="Input" name="inputTest">
<button type="submit" class="formBtn">Absenden</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>
Upvotes: 0
Views: 523
Reputation: 12505
You are missing a line and need to modify your send()
line for sending POST content:
// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');
In the case of the send()
you have to turn the keys and values to a query string. I think this is why so many use jQuery
, it's done all this for you.
Upvotes: 1