I have an AJAX call that does not parse JSON properly. I get the error JSON.parse: unexpected end of data at line 1 column 1 of the JSON data . Is there a way to modify the post request so that I can parse the data correctly?
It’s not valid JSON, so you can’t parse it. Normally it means you’ve got something like an HTML error page (in which case the first character is <). If you don’t parse it and just inspect what it is, that would help
No, that’s not going to make any difference, unless you’re doing the wrong thing (ie if you are not supposed to be sending some data to an endpoint then parsing what the server sends back)
It’s either not JSON or something is wrong with the JSON (which amounts to the same thing). Just console log the data so that you can find out what you are getting
Okay I think then it’s probably string with double quotes so a string that is empty. Here is the getSongJson.php file I echoed my array from the database of songs into json.
<?php
include("../../config.php");
if (isset($_POST['songId'])) {
$songId = $_POST['songId'];
$query = mysqli_query($con, "SELECT * FROM songs WHERE id='$songId'");
$resultArray = mysqli_fetch_array($query);
echo json_encode($resultArray);
}
?>
If the requested JSON data contains syntax error but is at least valid JS, you can perhaps try:
JSON.parse(JSON.stringify(data));
I’m not sure at all if this will work and even if it works, it should only be a temporary solution for assisting you in investigating and rectifying the actual cause of the error.
You need to actually return valid JSON. An empty string is not valid JSON. So you need to make sure your PHP code is actually returning the right thing, the error is there, not with the JS code.
If there are no results for that query, and the query is an array, then it should be returning "[]". If there are results and you’re getting an empty string, then you need to fix that. But this is PHP, not JS.