I'm a beginner in JavaScript and started to see Ajax. I made an example where I have a form that sends a name to a php file. This php receives via post and writes the information in a txt. Home I am using Ajax to send the data and trying to request them to appear in a div, without refresh obviously, however, I am not able to request after sending.
Follow the codes
HTML
<form id="form" method="post" action="">
<label for="name">Nome:</label>
<input type="text" name="name" id="name">
<input type="submit" id="submit" name="submit" value="Enviar">
</form>
<div id="result"></div>
PHP
<?php
$name = "<p>" . $_POST["name"] . "</p>" . PHP_EOL;
$file = fopen("names.txt", "a");
fwrite($file, $name);
fclose($file);
?>
JavaScript
var btn = document.getElementById("submit"),
result = document.getElementById("result"),
ajax = new XMLHttpRequest();
function sendData() {
"use strict";
var name = document.getElementById("name").value;
ajax.open("POST", "_names.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("name=" + name);
}
function loadData() {
"use strict";
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
result.innerHTML = ajax.responseText;
}
};
ajax.open("POST", "names.txt", true);
ajax.send(null);
}
window.onload = loadData();
btn.onclick = function () {
"use strict";
sendData();
return false;
};