1
I’m a beginner in Javascript and I 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.
I am using Ajax to send the data and trying to request them to appear in a div, without refresh obviously, however, I am unable to order after sending.
Follows 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;
};
Which doubt???
– Papa Charlie
I can send the data to the file, but the result only appears if I refresh the page. This is the problem
– Marlom
If you want to send and retrieve the name, you don’t need PHP to return the content again, just the status of success... use the
var name
.– Papa Charlie
PHP is only writing the information in txt. Ajax sends the data to php, php stores in txt, and then ajax searches for this data in txt.
– Marlom
PHP is successfully writing the name in the file?
– Papa Charlie
Already tried to make a single request, and reply from php itself?
– bfavaretto