0

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"}]
5
  • 1
    for starters is success firing? where is your ajax error handler? Your CORS configuration looks to be lacking several other Access-Control headers Commented Jun 5, 2016 at 19:36
  • 2
    What do you get if you alert my_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 use console.log() instead of alert() and check your browser's console for the output, which should let you explore the output. Commented Jun 5, 2016 at 19:43
  • @charlietfl for my CORS (forget about them. I added one line but they are ok ) ... Next is the error hadling. Dont bother about it as this script was used in a case "Hello world " before and it worked. The only thing now is the fact that it a multidimentional array and also that I want to use a global variable Commented Jun 5, 2016 at 19:46
  • @xjstratedgebx Ok I think the problem is solved. my_data[0].id just printed "1".... BUT I stil cant get it in my global variable my_data Commented Jun 5, 2016 at 19:50
  • 1
    ajax is asynchronous. You can't access the data in alert outside of it because it hasn't been returned yet. You need to consume it inside success. Don't use alert for debugging data/variables....use console Commented Jun 5, 2016 at 19:50

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

ok I get. I was able to access it with my_data[0].id Any idea how I could define my_data with the data coming from the success function and use is later ?
One way to use it 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.
omg. For a beginner thats a lot. I hot using it in the success callback will help me. I'll look into promises and generators. Thanks mate.
No problem. Enjoy.
1

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

"you have to call that ajax with async: false" shouldn't even be a topic of discussion other than to say never use it.... it is a terrible and flawed concept. It is also now deprecated by browser vendors and warnings are being logged in console if you do use it
@charlietfl good tip, i will update my answer with your comment.
0

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

cool. If I'm correct then I have defined it as I should in the success. But since ajax is asynchronous, at what point am I going to be able to access it ? (changing the position in the script will help ?
There is no saying when you will be able to access. You could try a 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.
Ok mate thank you. Raphael said that too. I'll just add the code in the success callback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.