...

View Full Version : PHP return JSON



jonatec
02-21-2012, 05:03 PM
Hi

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;
mysqli_close($dbc);
}

cercos
02-21-2012, 10: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) {
if(buf)
{
//reutrned true do something good
}
else
{
//returned false do somthing evil
}
}, 'json');

jonatec
02-23-2012, 11:15 AM
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 ??

Cheers.

jonatec
02-23-2012, 03:40 PM
Just cracked it! Thanks, the method to use an array was useful and I used:
print_r(json_encode($array));
to inspect the json.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum