Jason Krs Jason Krs - 8 months ago 33
Javascript Question

Access multidimentional PHP array in Jquery Ajax

I have a php script running a SQL query on my MSSQL Server instance. I get a good result. Now I'm trying to manipulate its result from $.ajax But It seems that the "Object.field_name" way of acessing fields in an obejct table is not working in my Jquery Ajax (maybe because there is more that one line returned)

The table is json_encoded in php. Could you help me access these data and put it in a global vairable ?

PHP script

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json'); //Newly added
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

try {
$hostname = "SQLEXPRESS";
$port = 1433;
$dbname = "MY_BD";
$username = "user";
$pw = "password";
$dbh = new PDO ("sqlsrv:Server=$hostname,$port;Database=$dbname","$username","$pw");
}catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";

$stm = $dbh->prepare("SELECT * FROM dbo.emp");

$table_1 = array();
while($row = $stm->fetch(PDO::FETCH_ASSOC)){
$table_1[] = $row;

echo json_encode($table_1);


Javascript script

var my_data ;

function get_my_data(){

type: 'POST',
url: 'http://localhost:8012/My_Script/test_1.php',
dataType: "json",
crossDomain: true,
success: function(result) {
my_data = result;
alert(my_data); //This will alert [Object object]
alert(my_data.id); //This will alert undefined ; id being on of the
//result fields

alert(my_data); //This will alert undefined (not even [Object Object]
//as if the global variable my_var can't be access in the $.ajax part
$( document ).ready(get_my_data);

Whithout Jquery Ajax, the output of my php script in the browser is :



The problems are:

1: You are not accessing my_data properties correctly. my_data is an array of objects. To access the first object's id property, use my_data[0].id.

2: The last alert(my_data); directly above $( document ).ready(get_my_data); is called before my_data gets defined. This is because $.ajax is asynchronous.