The site has a button (Create page) and input is next to it:

enter image description here

The code is:

<a class="sidebar-toggle" > <button style="background:transparent; border: 0; ">Создать страницу:&nbsp;&nbsp;&nbsp; </button> <input style="background: #3e95c7; border: 0; outline:none;" type="text" value=""> </a> 

By pressing the button, by the way, it is not enclosed in the <form> , I save the contents of <div class="getcode">некий текст</div> on the server as an html file: enter image description here

The mechanism for sending content to the handler on JS:

 var button = document.querySelector("button"); button.addEventListener("click", sendSave, false); function sendSave() { var data = document.querySelectorAll(".getcode"); var formData = new FormData(); for (var i = 0; i < data.length; i += 1) { formData.append("data[]", data[i].innerHTML); } 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); } 

Next on the server data is captured and placed in a file with the following php code:

 <?php $fp = fopen(date('Ymdhis').'-data.html', 'w'); $html = ""; foreach($_POST[data] as $data) { $html .= $data.PHP_EOL; } echo (fwrite($fp, $html)) ? "Сохранено" : "Не сохранено"; fclose($fp); ?> 

The file name is automatically generated, so that the file name is captured from inputa when saved and transferred to the handler at the touch of a button and entered instead of the currently generated current date:

enter image description here

  • $fileName = $_POST['input_name']; - rjhdby
  • @rjhdby how to screw it to my code, for the solutions I already nahordil but screwing they did not work what to add in JS that in PHP? Tell me the answer, please, like a simple task but I can master it - Pavel

1 answer 1

Add to input id="filename"

 <input style="..." id="filename" type="text" value=""> 

Add to the end of the function sendSave()

 formData.append("filename", document.getElementById("filename").value); 

In php script

 $filename = $_POST['filename']; 
  • and in php where to insert it? - Paul
  • I did so, at the beginning of the php file I inserted the line $ filename = $ _POST ['filename']; And the 2nd line was modified like this: $ fp = fopen ($ filename .'- data.html ',' w '); After that, the file is saved only once, with the name [object HTMLInputElement] -data.html, and all and more saves do not occur (do not occur apparently due to the fopen function that creates the file only if the name does not exist, otherwise overwrites) - Pavel
  • @Paul oh, damn it. Sorry, I'll fix it now :) - rjhdby
  • @Pavel Updated answer. Of course, you need to take its value from input - rjhdby
  • Thank you earned, thanked the rep increase) - Paul