Jason Krs Jason Krs - 5 months ago 19
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

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

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

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

$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(){

$.ajax({
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 :

[{"id":"1","name":"John","sal":"1525.21","age":"45"}]
[{"id":"2","name":"Cecily","sal":"854.75","age":"28"}]
[{"id":"3","name":"Alfred","sal":"945.28","age":"37"}]

Answer

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.

Comments