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":"[email protected]","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.

3
  • possible duplicate of How to return AJAX response Text? Commented Sep 10, 2013 at 9:32
  • are you accessing sineData outside the success function? Commented Sep 10, 2013 at 9: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 Commented Sep 10, 2013 at 9:38

1 Answer 1

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");
      }
  })
Sign up to request clarification or add additional context in comments.

3 Comments

still getting undefined, and no log. Why wouldnt it be whenIsDone(result) here BTW? (tried that to but of course that didnt work)
"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?
Could you post the complete non-working-code on jsfiddle.net ?

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.