Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created February 25, 2020 11:37
Show Gist options
  • Save Nekodigi/1ee9d21b9d5f8c2c318710439bae88e6 to your computer and use it in GitHub Desktop.
Save Nekodigi/1ee9d21b9d5f8c2c318710439bae88e6 to your computer and use it in GitHub Desktop.
Simple Comment system
function onClickBtn(){
var val = document.querySelector('#msg').value;
var form = new FormData();
form.append('msg', val);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/comment.php', true);
xhr.onload = function(e){
if(this.status == 200){
var result = this.response;
var comments = document.querySelector('#comments');
comments.innerHTML = result;
}
}
xhr.send(form);
}
<?php
$msg = '';
if(isset($_POST['msg'])){//check existance of message data
$msg = htmlspecialchars($_POST['msg']);//XSS attack contermeasures
$f = @fopen('savedata.txt', 'a');
fputs($f,$msg."\n");//write data
fclose($f);
$data = @file('savedata.txt');//open file as list
$data = array_reverse($data);
foreach($data as $line){
echo "{$line}<br>";
}
}else{
echo "writing failed";
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Comments</title>
<script src="/comment.js" charset="utf-8"></script>
</head>
<body>
<h1>Comment test</h1>
<input type="text" id="msg">
<button onclick="onClickBtn();">Submit!</button>
<hr>
<p id="comments"></p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment