views:

23

answers:

2

OK, so I want to get a row of data from a DB via jQuery.ajax()

Here is the code where I want to load it:

$.ajax({
  url: 'mypage.php?id=345',
  success: function(data) {
    //process array of data
  }
});

Here is the code on the page that jQuery is loading from:

$DBH = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

$STH = $DBH->("SELECT * FROM mytable WHERE id = :id");    

$STH->setFetchMode(PDO::FETCH_ASSOC);

$data = array( 'id' => $_GET['id']);  
$returnArray = $STH->fetch($data);

// How do I return $returnArray as an Array to jquery?

Not sure what to do to return the array. I guess I can implode() it as a string and then split() once returned but I thought there might be a better way.

Also, I am new to using PDO so if I did it wrong please let me know. Thanks.

+4  A: 

Use json_encode() - you can read that in Javascript natively.

Pekka
will also need to specify dataType: 'json', in the `$.ajax()` call or send back a JSON mime-type, in order that jquery will read the response correctly
Tom Haigh
@Tom I used $.getJSON instead of $.ajax
John Isaacks
@John Isaacks: ah ok. it was just the example used $.ajax().
Tom Haigh
@Tom right, I originally planned to use $.ajax but did a google search on jquery json after reading this answer and found the getJSON method. But thanks for the comment, it can save someone a headache!
John Isaacks
A: 
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$testArray=array('a'=>array('b','c'));
print Zend_Json::encode($testArray);
Pavel Mushroom