0
$(function() {

    var sineData;

    $.ajax({
        url : '../_php/loadFromDB.php',
        type : 'POST',
        data : 'getSines',
        dataType : 'json',
        success : function (result) {
            console.log(result);
            sineData=result; 
        },
        error : function () {
           alert("error");
        }
    })

});

Under Console->All->Response in firebug I get the below as expected:

[{"userID":"1","email":"user@mail.com","number":"800.256.6547","ext":"5788","startDay":"Sunday","endDay":"Thursday"}]

but when I look at sineData it is Undefined.

I want to be able to access these values like sineData[0].email

Where am I going wrong?


async: false, ended up fixing this for me but probably isnt the best solution for most aplications.

Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Sep 10 '13 at 09:32
  • are you accessing `sineData` outside the `success` function? – Khanh TO Sep 10 '13 at 09:35
  • @Khanh TO , Id like to yes. I was under the impression I could do that by decalring the var at the top and assigining it a value in `success` – Wesley Smith Sep 10 '13 at 09:38

1 Answers1

1

You are probably accessing sineData outside the ajax call. You are trying to access it before the asynchronous call is done. Try this:

function whenIsDone(result){
  // Do whatever you want with the variable result
  console.log(result[0].email);
}
    $.ajax({
        url : '../_php/loadFromDB.php',
        type : 'POST',
        data : 'getSines',
        dataType : 'json',
        success : whenIsDone,
        error : function () {
           alert("error");
      }
  })
ianaz
  • 2,490
  • 3
  • 28
  • 37
  • still getting undefined, and no log. Why wouldnt it be whenIsDone(result) here BTW? (tried that to but of course that didnt work) – Wesley Smith Sep 10 '13 at 09:50
  • "You are trying to access it before the asynchronous call is done." that got me thinking, adding `async: false,` makes my original code work. The object I will be returnin will only ever be 10-15 rows long so I dont think not being asynchronous will be an issue, right? – Wesley Smith Sep 10 '13 at 09:58
  • Could you post the complete non-working-code on jsfiddle.net ? – ianaz Sep 10 '13 at 10:57