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
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.