Skip to content
Advertisement

Unexpected number showing up at the end of JSON body

I am trying to write a simple demo that reads a json file with php and ajax. In js I have

// initial entry point
function main(){
    var button = document.getElementById("button");
    button.addEventListener("click",test);
    button.addEventListener("click",getSummary);
}

function test(){
    console.log("button was clicked");
}

function getSummary(){
    asyncRequest = new XMLHttpRequest();
    asyncRequest.addEventListener("readystatechange", processResponse, false);
    console.log("sending request");
    asyncRequest.open("GET","http://localhost/summary.php",true);
    asyncRequest.send(null);
}

function processResponse(){
    console.log("processing request");
    if(asyncRequest.readyState==4 && asyncRequest.status==200){
        console.log(asyncRequest.response);
    }
}

summary.php

<?php
$data = readfile("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo json_encode($data);

summary.json

{
    "products":[
        {
            "product":"professional pencil",
            "image":"pencil.jpg",
            "description":"The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
        },
        {
            "product":"coffee mug",
            "image":"coffee_mug.jpg",
            "description":"Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
        },
        {
            "product":"programming book",
            "image":"programming_book.jpg",
            "description":"Learn how to program effectively by reading this book."
        }
    ]
}

When I make a request I get an unusual 706 at the end of the response. curl localhost/summary.php | Select Content -Expand Content | jq produces

{
  "products": [
    {
      "product": "professional pencil",
      "image": "pencil.jpg",
      "description": "The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
    },
    {
      "product": "coffee mug",
      "image": "coffee_mug.jpg",
      "description": "Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
    },
    {
      "product": "programming book",
      "image": "programming_book.jpg",
      "description": "Learn how to program effectively by reading this book."
    }
  ]
}
706

Any help with this would be greatly appreciated.

Advertisement

Answer

For your summary.php you actually want it to be more like the following to do what you are intending to do

<?php
$data = file_get_contents("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo $data;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement