0

Having some issues getting my head around JS scope. I know its not AJAX , as I've turned async:false, but I couldn't get jQuery Promise to work for me. I really cannot understand as to why apiData gets returned undefined.

 var url = 'http://www.myjson';      

    /* The API call */
    function getData(url) {

        var text;

        result = $.ajax({
            type: 'GET',
            url: url,
            async: false,
            jsonp: 'callback',
            dataType: 'jsonp',
            success: function(data)
            {
                text = data;
                 //console logging here returns text data fine
                return text;
            }

         });

        return text;
    }
    apiData = getData(url);
    console.log(apiData);

    //returns undefined for apiData

2 Answers 2

3

It does not look like synchronous calls are allowed with cross domain requests.

According to jQuery documentation:

"Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation"

http://api.jquery.com/jQuery.ajax/

I have not tested, but maybe async is changed to "true" in your case, since you are using jsonp as datatype. Therefore, the onSuccess handler has not been called before you try to read the data.

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

1 Comment

yes, this was it. Shame no error was thrown stating that this is the case. Thanks .
0

Try like this

var url = 'http://www.myjson';      

/* The API call */
function getData(url) {

    var text;

    result = $.ajax({
        type: 'GET',
        url: url,
        async: false,
        jsonp: 'callback',
        dataType: 'json',
        success: function(data)
        {
            text = data;
             //console logging here returns text data fine
            return text;
        }

     });
}
apiData = getData(url);
console.log(apiData);

//returns undefined for apiData

Comments

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.