Tag Archives: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse

[Solved] Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse

Ajax cannot get data:
Problem Description:
vm379:1 uncaught syntax error: unexpected end of JSON input at json.parseļ¼ˆ

Cause analysis:
1. The format of JSON data returned by the back end is incorrect
2. The method of JSON data returned by the back end is incorrect

Solution:
PHP:

  return json_encode(array(
         'status' => 3,
         'message' => 'Incorrect ID'
     ));

Replace with:

echo '{"status": 3, "mesg": "Incorrect ID" }';

Note: JSON strings should be enclosed in double quotation marks

Problem-solving

 // ajax
    function del_cate(id, pid) {
      if (window.XMLHttpRequest) {
        var xmrt = new XMLHttpRequest();
      } else {
        var xmrt = new ActiveXObject('Microsoft.XMLHTTP');
      }

      xmrt.onreadystatechange = function () {
        if (xmrt.readyState == 4 && xmrt.status == 200) {
          console.log(xmrt);
          console.log(JSON.parse(xmrt.responseText));
          var status = JSON.parse(xmrt.responseText);

          if (status.status == 1) {
            alert('Deleted successfully!');
            window.location.href = 'cate.php';
          } else if (status.status == 0) {
            alert('Deleted successfully!');
            window.location.href = 'cate.php';
          } else {
            alert('Deleted successfully!');
            window.location.href = 'cate.php';
          }
        }
      }
      xmrt.open('DELETE', './del_cate.php?id=' + id + '&pid=' + pid, true);
      xmrt.send();
    }