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"}]
successfiring? where is your ajax error handler? Your CORS configuration looks to be lacking several otherAccess-Controlheadersmy_data[0].id? Looks like your results are an array of objects, although I can't tell if you have shown three separate results, or 1 result with 3 rows? Also, you'll get way more data if you useconsole.log()instead ofalert()and check your browser's console for the output, which should let you explore the output.my_data[0].idjust printed "1".... BUT I stil cant get it in my global variablemy_data