FormData third parameter, just the same, the name of the file that will be sent to the server (USVString) when Blob or File passed the test as the second parameter. The default filename for Blob objects is "blob".
Example:
var formData = new FormData(); // Currently empty formData.append('username', 'Chris'); formData.append('userpic', myFileInput.files[0], 'chris.jpg');
reference
Accordingly, the values of the input are passed by the third parameter and it seems like this is all. On the server, respectively, get out.
For example, input <input type="text" id="test" value="myTextValue"> , we get this way:
var txtName = document.querySelector('#test').value;
We pass:
var txtName = document.querySelector('YOUR_SELECTOR').value; var formData = new FormData(); // Currently empty formData.append('username', 'Chris'); formData.append('userfile', myFileInput.files[0], txtName);
The truth is as far as files are concerned ..
If you pass a string in the value, then from the input you also need to add a new passed parameter with your key, but with the value from the input, i.e.
var data = document.querySelector(".getcode").innerHTML; var fileName = document.querySelector('YOUR_SELECTOR').value; var formData = new FormData(); // Currently empty formData.append('data ', data); formData.append('fileName', fileName);
On the server, catch the variable from $_POST['fileName']
Total
HTML
<div class="getcode">Наполняемый контент, другие div блоки</div> <button>Получить и сохранить сожержимое</button> <input type="text" id="fileName" value="myTextValue">
Js
var button = document.querySelector("button"); button.addEventListener("click", sendSave, false); function sendSave() { var data = document.querySelector(".getcode").innerHTML; var fileName = document.querySelector('#fileName').value; var formData = new FormData(); formData.append('data', data); formData.append('fileName', fileName); var XHR = "onload" in new XMLHttpRequest() ? XMLHttpRequest : XDomainRequest; var xhr = new XHR(); xhr.open('POST', 'save.php', true); xhr.onreadystatechange = () => { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(formData); }
Php
$fp = fopen($_POST['fileName'], 'w'); // $fp = fopen($_POST['fileName'].'-data.html', 'w'); $html = $_POST['data'].PHP_EOL; echo (fwrite($fp, $html)) ? "Сохранено" : "Не сохранено"; fclose($fp);