As for vanilla js to send the contents of a text form field in json format using ajax and get response from the server, the same string?

Can't find the error... when you click on the button nothing happens...
<form id="form-name">
 <input type="text" name="name" id="text-field">
 <input type="text" name="response" id="response-field">
 <button type="submit" id="btn">Click me</button>
</form>

window.onload = function() {

 var form = document.getElementById('form-name');
 var textField = document.getElementById('text-field');

 form.onsubmit = function() {
 var request = new XMLHttpRequest();
 var text = textField.value;
 request.open('POST', 'script.php', true);

 request.onreadystatechange = function() {
 if (this.readyState === 4 && this.status === 200) {
 document.getElementById('response-field').value = this.responseText;
 // console.log(this.responseText);
}
};

 var date = {name: text};
 request.setRequestHeader('Content-type', 'application/json');
request.send(JSON.stringify(date));
 return false;
};

};

if (isset($_POST['name'])) {echo json_encode($_POST['name']);}
July 2nd 19 at 18:23
1 answer
July 2nd 19 at 18:25
Solution
Your problem is on this line
if (isset($_POST['name'])) {echo json_encode($_POST['name']);}

You pass to the server not the form but the content as JSON which does not decode to PHP $_POST
Moreover should get a warning about the fact that "Populating the raw post data is deprecated"
In order for You to get on the server the raw data is necessary to pick them up, like so:
$data = file_get_contents('php://input');

And in order not to have errors in php.ini to put
always_populate_raw_post_data = -1

With Vanilla JS and all is well.

Find more questions by tags AJAXPHPJavaScript