I am doing a $.ajax(type: 'GET', data: ticket)
where ticket
is an authentication token. ticket
is acquired like so:
var newTicket = $.ajax({
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'JsonPCallBack',
data: {},
url: "https://api.examample.com?username=bar&password=foo",
});
Once I have obtained my ticket
I can do my GET
:
function getData(ticket, query) {
return $.ajax( {
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'JsonPCallBack',
data: ticket,
url: "https://api.examample.com/?data=" + query,
});
}
Putting it together:
newTicket.done(function(ticket) {
var ticket = ticket;
getData(ticket, query).done(function(result) {
console.log(result);
});
});
This works perfectly fine - my two calls are definitely working.
My challenge is that I want to make this call again for a many values of query
. Here is what I tried:
// example.com promises me that I can use ticket for multiple requests
// for one ticket I will try and do multiple requests
newTicket.done(function(ticket) {
var deferred = $.Deferred();
var ticket = ticket;
// Inspired by http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when
requests = [];
for (i in queries) {
query = queries[i];
requests.push(getData(ticket, query));
}
$.when.apply($, requests).done(function(result) {
for(var i = 0; i < arguments.length; i++) {
console.log(calculateData(arguments[i][0]));
}
});
});
This however does NOT work. I cannot figure out why. Any advice?
I tried adding this code:
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('jqXHR: ' + jqXHR);
console.log('textStatus: ' + textStatus);
console.log('errorThrown: ' + errorThrown);
});
And this gave me:
jqXHR: [object Object]
textStatus: parsererror
errorThrown: Error: JsonPCallBack was not called
UPDATE: The simple case with only one request does not work if I do not specify jsonp and JsonPCallBack. It does work if I specify jsonp and JsonPCallBack.
I tried running the code with two requests in my array. Sniffing the packets I see that two requests are made with Status Code 200 OK. The response starts with JsonPCallBack({
and contain the correct data. So when I look at the actual repsonse everything looks correct. Why do I reach .fail()
?