Reading json data from php file in a server


#1

Hi guys,

I am trying to read the json data from a php file which is in a server. My php file outputs an array using json_encode but in ionic 2 i get an error saying “Unexpected token < in JSON at position 38”

I did a lot of research and still it is not working.

my php file is like this

    <?php
    header("Access-Control-Allow-Origin: *");
    // header('Content-type: text/javascript');
    //open connection to mysql db
    $connection = mysqli_connect("xxxx.000webhost.com","xxxx","xxxx","xxxxx") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from Test";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);
    // output of this echo is '[{"name":"Hello","version":"World"}]';

    //close the db connection
    mysqli_close($connection);
?>

my ionic 2 .ts function for getting data is this

getDataFromServer(){
  this.http.get('http://emebedintime.comxa.com/getTrainInfo.php')
  .map(res => res.json())
  .subscribe(data => {
        // console.log(data);
        this.posts = data;
        // console.log(this.posts);
    });
}

any help?


#2

I solved this problem. This happened because the web hosting site has added some analytics code. I edited the .htaccess file to remove that code. Below code was added and now it is working

<FilesMatch "\.(php)$">
php_value auto_append_file none
</FilesMatch>