Tuesday, January 3, 2012

Example: php json_encode json string put into javascript object array

//javascript:
...
//myjsonstring will catch the string returned from the url, getmydata.php
var myjsonstring = $.ajax({
url: 'getmydata.php',
async: false,
success: function(data, result) {
if (!result) { alert('Failure to retrieve the items.'); }
}
}).responseText;

var myDataStore =  $.parseJSON(myjsonstring);
//then, I can get any field in any row that are stored in myDataStore
// e.g. var l_fname = myDataStore[0].firstname; //the first row of data

//getmydata.php
...
$tsql = "EXEC proc_sel_my_data ?, ?"; //says 2 args
$param1 = "*"; $param2 = "*";
$params = array( &$param1, &$param2);
sqlsrv_query($conn,"SET CHARACTER SET 'utf8'"); //I'm using sqlserver
if ($stmt = sqlsrv_query( $conn, $tsql, $params)) {
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){ //fetch each row and put into an array
$data[] = $row;
}
// print_r($data);
} else { echo 'Query fail.';}

echo json_encode($data); // encode the $data array to json, and it'll be return to ajax

p.s. PHP 5.3.8, Apache 2.2.21, PHP SQL Server 2.0.1, jquery 1.6.2

No comments: