1

I have a created a PHP class that retrieves all the data from a database and gets back the results in JSON format:

public function getCategories() {
    if (!$this->isConnectionAlive()) {
        $this->getConnection();
    }

    $data = $this->dbconn->prepare("SELECT DISTINCT cat FROM regalo");
    $data->execute();
    $results=$data->fetchAll(PDO::FETCH_ASSOC);
    $json_data = json_encode($results);
}

then an object of the class calls this method and is able to successfully do exactly that:

$dbh = new DatabaseHandler('localhost', 'fakeuser', 'fakepass', 'fakedb');

$dbh->getCategories();

How do I pass this data to my AJAX script so that it can manipulate the JSON-formatted results?

2
  • @Ethan yes, I should have mentioned that. Commented Feb 17, 2013 at 19:16
  • 2
    Your getCategories method should return $json_data and you should echo the call to that method at an URL your AJAX script can access Commented Feb 17, 2013 at 19:17

1 Answer 1

3

This should do it in your javascript:

$.get('/getCategories',null,function(response){
  console.log(response);
},"JSON");

And you need to be echo-ing your json encoded data in the php script

public function getCategories() {
    if (!$this->isConnectionAlive()) {
        $this->getConnection();
    }

    $data = $this->dbconn->prepare("SELECT DISTINCT cat FROM regalo");
    $data->execute();
    $results=$data->fetchAll(PDO::FETCH_ASSOC);
    $json_data = json_encode($results);
    header('Content-type: text/json');
    header('Content-type: application/json');
    echo $json_data;
}

I would actually throw that into it's own thing for re-use later on too:

public static function send_json_data($php_array)
{
        header('Content-type: text/json');
        header('Content-type: application/json');
        echo json_encode($php_array);
        exit(); //if you have hooks or something else that executes after output in your script, take this line out.
}
Sign up to request clarification or add additional context in comments.

3 Comments

You should terminate the script after the echo to prevent any code, wanted or not, from being output (such as errors/warnings/notices)
In a production environment errors should be turned off, but I added an exit() either way.
Agreed, though in practice a site should have a dev and production environment and your code should work on both in my opinion. +1 for the separate json function. You could take it one step further and check for headers_sent() before output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.