I've created a form where users can insert their name and message, and when they press on the submit button the data will be posted to ajax/returnJson.php
. In ajax/returnJson.php
, the name and message will be pushed into data.json
. After data.json
is updated, the desired result is it returns the newly added name and message in json format to Ajax. However, I keep on getting this error: Syntax error:Unexpected token < in JSON at position 0
. Here is my code:
show_topic.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ChatSpace</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/0.9.90/jsrender.js"></script>
<script src="jquery.miranda.min.js"></script>
</head>
<body>
<h1>ChatSpace</h1>
<h2>雑談</h2>
<div class="w3-container">
<table id = "posts" class="w3-table w3-bordered w3-striped">
</table>
</div>
<form>
名前:<br>
<input type="text" id="username" name="username"><br>
本文:<br>
<input type="text" id="messageBody" name="message"><br>
<button type="button" id="submitBtn" class="btn sendBtn">投稿</button>
</form>
<script type="text/javascript">
var dataList = [
{
"user": "Aさん",
"message": "こんにちは"
},
{
"user": "Bさん",
"message": "初めまして"
},
{
"user": "Cさん",
"message": "よろしくお願いします"
}
];
$.getJSON("ajax/data.json", {name: "freeTalk"}, function(data){
var dataArray = data.freeTalk;
$.each(dataArray, function(i){
$("#posts").append("<tr><th>" + dataArray[i].user + "</th></tr>");
$("#posts").append("<tr><td>" + dataArray[i].message + "</td></tr>");
});
});
$("#submitBtn").on("click", function(event){
name = $("#username").val();
message = $("#messageBody").val();
$.ajax({
url: 'ajax/returnJson.php',
type: 'POST',
data: {
"username": name,
"message": message
},
dataType: "json",
})
.done(function(data){
var dataArray = array(data);
$("#posts").append("<tr><th>" + data.user + "</th></tr>");
$("#posts").append("<tr><td>" + data.message + "</td></tr>");
console.log("success");
})
.fail(function(XMLHttpRequest, textStatus, error){
console.log(error);
alert(error);
});
});
</script>
</body>
</html>
ajax/returnJson.php
<?php
header("Content-type: application/json; charset=utf-8");
$data = array("user" => $_POST['username'], "message" => $_POST['message']);
$string = file_get_contents('./data.json');
$json = json_decode($string);
array_push($json->freeTalk, $data);
$returnData = json_encode($data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
file_put_contents("data.json", $jsonData);
echo $returnData;
exit;
?>
data.json
{
"freeTalk": [
{
"user": "Aさん",
"message": "こんにちは"
},
{
"user": "Bさん",
"message": "初めまして"
},
{
"user": "Cさん",
"message": "よろしくお願いします"
}
]
}
Any help, please?