0

I am passing sql table rows to a javascript file to be shown once the website page has loaded:

php code:

 $sql = "SELECT * FROM `publication_information`";
    $pubs = $conn->query($sql);
    
    while ($row = mysqli_fetch_assoc($pubs)) {
      $existing_publications[] = $row;
    }  
        $willies = json_encode($existing_publications);
        echo $willies;
        

javascript code:

function WORK(){
    var xhr = new XMLHttpRequest();
    var url = "/shoba/publications.php";
    
    
     xhr.onreadystatechange = function() {
      // Check if the request is completed and successful
      if (xhr.readyState == 4 && xhr.status == 200) {
        // Parse the JSON response
        var data = JSON.parse(xhr.responseText);
 
        // Do something with the data
        console.log(data+" success");
      } else {
          console.log(error);
      }
    };
    xhr.open("GET", url, true);
    xhr.send();
    alert("reached function end");
}

on calling the function, the alert is reached but i get the uncaught error:

VM65:1  Uncaught SyntaxError: Unexpected end of JSON input

But I cannot spot what is wrong, to my knowledge , since I used an auto function it should work, but it sadly does not. Can you help tell me what's wrong?

ThW
  • 19,120
  • 3
  • 22
  • 44
Shoba
  • 1
  • 2

1 Answers1

0

Unless guaranteed to be properly formed, it is recommended to use try..catch block when parsing a JSON string.

The example below gives you what the problem was and the content causing the parser to fail.

var responseText = xhr.responseText;

try {
  var data = JSON.parse(responseText);
  console.log(data);
} catch (ex) {
  console.warn(ex.message);
  console.info('"' + responseText + '"');
}

I'm not sure what's wrong with the PHP side but here, we see that the json_encode may return null. Have you checked what JSON string is returned if $pubs has no items or null?

Bulent Vural
  • 2,630
  • 1
  • 13
  • 18