0

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?

sttc1998
  • 51
  • 2
  • 10
  • 1
    The error message suggests you aren't getting that JSON back but likely HTML instead. Very likely your server encounters an error and sends back an error page (so, HTML) which when parsed into JSON stops at the first opening of a tag `<` – VLAZ Jan 14 '20 at 08:07
  • After your `$.getJSON("ajax/data.json"`, what response does appear in the developer tools' Network tab? (And it is an HTML with 404 message?) – mbojko Jan 14 '20 at 08:09
  • Use console.log() and check what you are getting from the server. As VLAZ suggested, it might be some HTML instead of JSON. Based on what you are getting in console.log() you can debug your code. – Not A Bot Jan 14 '20 at 08:13
  • @NotABot `console.log` likely wouldn't work, since the conversion from JSON will be handled automatically by jQuery. Which also means you get an error before you can see the result. You can disable jQuery's processing of the results and then log the JSON but it's too much hassle - just check the Network tab and/or debug what the server is doing. – VLAZ Jan 14 '20 at 08:16
  • @VLAZ Yes you are correct, but what I meant to say that use kind of any error catch mechanism, like `error(function(err) { console.log("Error is: "+err); })` to check where is the problem. – Not A Bot Jan 14 '20 at 11:18
  • @NotABot it already tells you - the first character is `<` which is not valid for that position. There is no more the error can tell you. Unless you examine the callstack, in which case there is pretty much nothing at all - you'd see a rather deep callstack of just jQuery calling other jQuery ending with something like `parseJSON`. At best, you will be able to find the root function that causes some invalid JSON to be parsed yet *you already know that* - it's the AJAX call. All of that information should be available without using `console.log` - just by looking at the dev tools. – VLAZ Jan 14 '20 at 11:22
  • Thank you for your reply. Error thrown is ```SyntaxError: Unexpected end of JSON input at parse () at Qb (jquery-3.2.1.min.js:4) at A (jquery-3.2.1.min.js:4) at XMLHttpRequest. (jquery-3.2.1.min.js:4)``` and there is no response data with status 200 OK. – sttc1998 Jan 15 '20 at 00:13

0 Answers0