简体   繁体   中英

Ajax call returns SyntaxError: Unexpected end of input

I am working on a very simple notepad application. The user may fetch "a file" (in reality it is just a row from MySQL) to edit it.
When submitting the form directly to the php file ( just remove e.preventDetfault ), the output is the json encoded output I want:

{"data":{"filename":"testfile","content":"this is the file content","lastupdate":"2016-03-06 13:13:30"}}

However, when ran through the below Ajax call, it always returns SyntaxError: Unexpected end of input.

The form

<form id="openfile" action="backend.php" method="POST">
<input type="text" name="filename" placeholder="Enter filename to open" id="filename" />
</form>

The jQuery AJAX call

$("#openfile").submit(function(e) {

  var filename = $("#filename").val();

  openFile(filename);

  e.preventDefault(); 

});


function openFile(filename) {

  if(filename == "") {
    return false;
  }


  $.ajax({
         type: "POST",
         url: "backend.php",
         data: {action: "load", file: filename},
         success: function(response) {
         console.log(response);
         },
         error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log("Status: " + textStatus);
            console.log("Error: " + errorThrown);
        }
       });

}

The backend

      try {

        $db = new PDO(DB_DSN, DB_USER, DB_PASS);
        $sql = "SELECT `filename`, `content`, `lastupdate`
                FROM `notepad`
                WHERE `filename` = :filename
                LIMIT 1";
        $sth = $db->prepare($sql);
        $sth->bindParam(":filename", $_POST['file'], PDO::PARAM_STR);
        $sth->execute();

        if($sth->rowCount() != 0) {
          $result = $sth->fetch(PDO::FETCH_ASSOC);
           $response['data'] = $result;
          //echo json_encode($result);
        } else {
          $response['error'] = "File does not exist";
        }

      } catch(PDOException $e) {
        $response['error'] = $e->getMessage();
      }

      // Return json data
      echo json_encode($response);

I know for sure the correct data is being sent (chrome dev tools -> network).

Using a nearly identical ajax call to save a file works just fine.

Your question is similar to: Chrome: Uncaught SyntaxError: Unexpected end of input

Try to add headers application/json for your response:

header('Content-Type: application/json');
echo json_encode($response);

Have you tried specifying the dataType as Json?

ie

dataType: 'json',

in your Ajax call.

You're sending back a json object, but you haven't specified the return type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM