View Full Version : PHP return JSON

02-21-2012, 06:03 PM

Please take a look at the code section. Does anyone know how to:
a) Return JSON from the prepared procedure call instead of me using a while loop and a concatenated string?
b) Given the MySQL query returns these columns: ID, DepartmentName how do I access these in my client-side JavaScript, ie what will the JSON look like ?

Many thanks.

function fnGetDepartments() {

require ('mysqli_connect.php'); // Connect to the Db.
$sql = "CALL get_departments(?)";
$stmt = $dbc->prepare($sql);
if ($dbc->errno) {die($dbc->errno.":: ".$dbc->error);}
$stmt->bind_param("i", $prm);
$stmt->execute( );
if ($dbc->errno) {die($dbc->errno.": ".$dbc->error);}
$stmt->bind_result($id, $dept_name);
$buf = "";
while ($stmt->fetch( )) {
$buf .= $id . '^' . $dept_name . '|';
$buf = substr($buf, 0, strlen($buf)-1);
echo $buf;

02-21-2012, 11:55 PM
well if $buf is the data you want to return to javascript it would be:

echo json_encode($buf);

then to access it in javascript you would just reference it as the same variable name as the php script.
with jquery you could do something like:

$.post('/YOUR_PHP_SCRIPT.php', $('#YOUR_FORM').serialize(),
function(buf) {
//reutrned true do something good
//returned false do somthing evil
}, 'json');

02-23-2012, 12:15 PM
Thanks for getting back..

But can I use json_encode directly with $stmt and not have to build up a string, kinda defeats the object ??


02-23-2012, 04:40 PM
Just cracked it! Thanks, the method to use an array was useful and I used:
to inspect the json.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum