ejoe23
ejoe23

Reputation: 50

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine. I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.

Here is the PHP code to get the information from the database:

<?php

class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('website.db');
    }
}

$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>

Here is the JavaScript where the AJAX is located:

<script type="text/javascript">

 function getNews()
 {
     console.log("firstStep");
      $(document).ready(function()
      {

        console.log("secondStep");
        $.getJSON("http://localhost/getNews.php",function(result){

            console.log("thirdStep");
            $('news').append(result); // display result

                 });
       });
  }

I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.

This is the HTML it should be appending to: <div id = "newsEntry"> <news> test </news> </div>

Any help would be appreciated.

Upvotes: 0

Views: 276

Answers (2)

light
light

Reputation: 4287

By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.

Include this line before your echo:

header('Content-Type: application/json; charset=utf-8');

Edit

On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:

$array = $result->fetchArray(SQLITE3_ASSOC);  // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Upvotes: 1

Hauke P.
Hauke P.

Reputation: 2823

To find out what's going on, you might want to add an error handler:

$(document).ready(function() {
  $.ajax({
    url: "http://localhost/getNews.php",
    dataType: "json",
    success: function(result) {
      console.log("thirdStep");
    },
    error: function(err) {
      alert(err);
    }
  });
})

Upvotes: 1

Related Questions