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"}]
3 Answers 3
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.
4 Comments
my_data[0].id Any idea how I could define my_data with the data coming from the success function and use is later ?later is to put the code that needs to run after my_data is defined within the success callback. Another way is to use promises. If you have a nontrivial amount of logic, promises are generally better. Also have a look into generators.You can not access my_data from that scope because $.ajax is asynchronous.
But i can suggest you to do this way
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 is an array you can't alert it do console.log(my_data)
//alert(my_data.id); // you can't access id directly because it's an array
// rather you can do this way loop/map over it will return each array item
my_data.map(function(data) {
alert(data.id);
})
}
});
}
//as if the global variable my_var can't be access in the $.ajax part
$(document).ready(function() {
get_my_data();
});
2 Comments
I think what you are looking for is a way to iterate over the results.
$(my_data).each(function(index,value) {
alert(value.id);
});
should work. As for making this global. Declare the variable outside the call and set it in the success and you should be able to access it. The reason why it is undefined for you is that ajax is asynchronous and that call is executed before the server returns the value.
3 Comments
setTimeout for 5 seconds or so but it is a bad practice. You should have whatever code that needs to run after you get the values from your ajax request, called from the success callback function. You can set async:false in your ajax request but it is not the right way to do things.
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