vendredi 24 avril 2020

PHP returning HTML instead of json with json_encode

This is the first time I'm working with PHP and ajax, and I need to return a json-encoded array.

In my PHP file, I do this:

while($row = mysqli_fetch_array($res))
        {
            $url=$row['url'];
            $desc=$row['description'];
            $cat=$row['category'];

            $return_array[] = array("url" => $url, "desc" => $desc, "cat" => $cat);
        }
mysqli_close($con);
header('Content-Type: application/json');
echo json_encode($return_array);

However, when logging the error in ajax upon calling this, I get:

Something went wrong parsererror SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSON (jquery-1.9.1.js:541)
    at ajaxConvert (jquery-1.9.1.js:8246)
    at done (jquery-1.9.1.js:8050)
    at XMLHttpRequest.callback (jquery-1.9.1.js:8598)

Upon inspection in the "Network" tab, this is what the PHP returns, even though its header shows up correctly as "Content-Type: application/json":

<!DOCTYPE html>
<html>
<body>
    [{"url":"","desc":"","cat":""},{"url":"asfasfs","desc":"desc","cat":"cat"},{"url":"asfasfs","desc":"desc","cat":"cat"},{"url":"asfasfs","desc":"desc","cat":"cat"}]     
</body>
</html>

How can I fix this? Why is my PHP returning HTML instead of json?

To be clear, the result array inside the body tags is correct, taken directly from my database.




Aucun commentaire:

Enregistrer un commentaire