I have a jQuery .each statement that loops through a set of accordion/panels
$("div.section-data-source").each(function () {
populateAccordion($(this));
});
For each element, I call a function (populateAccordion) which has an AJAX query with it's own done() callback.
How can I tell my each function to wait until the populateAccordion() function is completed before moving on to the next iteration? Can I have a deferred against the function itself - or is there a way for the function to tell the each to iterate?
function populateAccordion(el) {
var apiName = el.attr("data-source-api-name");
$.ajax({
type: 'GET',
url: api_URL + apiName + "/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(data) {
el.parent().find('.data-field').map(function () {
apiDataField = $(this).attr("data-field");
var itemValue = getApiDataValue(data, apiDataField, "Date");
$(this).text(itemValue);
});
});
console.log("FINISHED POPULATE");
};
Related
I'm trying to get a single image from each ajax request and append it to a li box container, the first ajax returns a list of 20 objects, with name and a url
$.ajax({
url: "http://pokeapi.co/api/v2/pokemon/",
dataType: "json",
method: "GET",
cache: false,
success: function(data) {
for (var i = 0; i<data.results.length ;i++){
$("#root ul").append('<li class="box"></li>');
$("li").eq(i).append('<h2>' + data.results[i].name +'</h2>');
}
setPkmImage(data.results);
console.log(data);
},
error: function(data) {
console.log("Error");
}
});
The problem starts when I try to make a call for each of those objects to request an image, it works with the async: false, but i don't want to do it that way since it takes a lot of time to load all the images.
function setPkmImage(res){
for (var i = 0; i < res.length; i++) {
var promise = $.ajax({
url: res[i].url,
dataType: "json",
method: "GET",
cache: false,
//async: false,
promise.done( function(data) {
console.log(data);
$("#root ul");
$("li").eq(i).append('<img src="' + data.sprites.front_default+ '"/>');
});
promise.fail( function(data) {
console.log("Error");
});
});
}
}
I'm trying to use promises but I don't know exactly how to structure it
Two major problems, one is syntax and the other is you need a closure loop
First the $.ajax is not closed properly.
Should look more like:
var promise = $.ajax({
url: res[i].url,
dataType: "json",
method: "GET",
cache: false
});
promise.done(...
promise.fail(...
As for the closure loop, i won't be what you want it to be inside the ajax callbacks because the for loop will have been completed before the data for requests is returned. Thus i will be at it's maximum by then
Try changing the for loop to $.each which creates a closure
$.each(res, function(i, item){
var promise = $.ajax({
url: item.url,
dataType: "json",
method: "GET",
cache: false
});
promise.done(...
promise.fail(...
})
I usually use the next solution. After first request is done, I've insert to dom img with url (url is come from request) and browser will load images automatically.
On my code I hava a function with 3 nested AJAX calls, in order for it to work I had to set Async=false.
As I have read that Async=false is deprecated I replaced the Async=false with promises.
This is my function before I edited it:
self.getOrders = function (name) {
var orders= [];
var order= function (item, type1, type2) {
var self = this;
self.order= item;
self.type1= type1;
self.type2= type2;
}
$.ajax({
url: "/API/orders/" + name,
type: "GET",
async: false,
success: function (orderResults) {
var mappedOrders = $.map(orderResults, function (orderItem) {
$.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET",
async: false,
success: function (property1Results) {
$.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET",
async: false,
success: function (property2Results) {
orders.push(new order(orderItem, property1Results, property2Results));
}
});
}
});
})
}
});
return orders;
This function worked perfectly, I got the data end everything worked fine.
Then I changed the function to use promises instead of Async=false,
this is the edited function, with promises:
//The begin of the function- same as first one
var orders= [];
var firstPromise = $.ajax({
url: "/API/orders/" + name,
type: "GET"
});
$.when(firstPromise).done(function (orderResults) {
var mappedOrders = $.map(orderResults, function (orderItem) {
var secondPromise = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET"
});
$.when(secondPromise).done(function (property1Results) {
var thirdPromise = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET"
});
$.when(thirdPromise).done(function (property2Results) {
orders.push(new order(orderItem, property1Results, property2Results));
});
});
});
});
return orders;
And the function call:
self.populateOrders = function (name) {
var mappedOrders = $.map(self.service.getOrders(name), function (item) {
return new Order(item)
});
self.orders(mappedOrders);
}
The new function is not working, I'm getting back from the firstPromise a wrong json with backslashes, and the returned orders object is empty.
Any idea what am I doing wrong? I spent so much time on it but couldn't figure it out.
Thanks in advance.
Nested ajax calls inside a loop is a hell to manage. You can do it like this.
Create a promise to notify the caller when the whole process is finished
Wait for all the inner ajax calls to resolve
Resolve you main promise to notify the caller
self.getOrders = function (name) {
var mainDeferred = $.Deferred();
var orders = [];
var order = function (item, type1, type2) {
var self = this;
self.order = item;
self.type1 = type1;
self.type2 = type2;
}
$.ajax({
url: "/API/orders/" + name,
type: "GET",
success: function (orderResults) {
var innerwait = [];
var mappedOrders = $.map(orderResults, function (orderItem) {
var ajax1 = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET"
});
var ajax2 = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET"
});
$.when(ajax1, ajax2).done(function (property1Results, property2Results) {
orders.push(new order(orderItem, property1Results[0], property2Results[0])))
});
innerwait.push(ajax1, ajax2);
});;
$.when.apply(null, innerwait) //make sure to wait for all ajax requests to finish
.done(function () {
mainDeferred.resolve(orders); //now that we are sure the orders array is filled, we can resolve mainDeferred with orders array
});
}
});
return mainDeferred.promise();
}
self.populateOrders = function (name) {
self.service.getOrders(name).done(function (orders) { //use .done() method to wait for the .getOrders() to resolve
var mappedOrders = $.map(orders, function (item) {
return new Order(item)
});
self.orders(mappedOrders);
});
}
In the example, note that I use $.when.apply() to wait for an array of deferreds.
A bug recently introduced in chrome 52 (august 2016) can cause this kind of behavior : answers for nested requested are ignored.
Hoppefully, it will not last long.
https://bugs.chromium.org/p/chromium/issues/detail?id=633696
Try to add cache: false
I have the following:
function wikiAjax (searchURL) {
return Promise.resolve($.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
}));
}
$(".search-form").submit(function() {
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.then(function(data) {
alert(data);
}, function() {
alert("The call has been rejected");
});
});
But i get an answer only if I put a breakpoint somewhere (e.g. at the wikiResponse.then line).
Then it looks like the code is executed before the call returns the result but why? Isn't the promise set properly?
Many thanks in advance.
I think what might be happening here is the browser is executing the default submit event on the form in addition to the ajax call. The result is that the window is unloaded and reloaded.
Try putting:
event.preventDefault();
in the handler.
$(".search-form").submit(function(event) {
event.preventDefault();
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.then(function(data) {
alert(data);
},
function() {
alert("The call has been rejected");
}
);
});
I think Promise.resolve() is an ES6 feature so unless you explicitly make sure you support it it should not work.
But, lucky for you $.ajax() return a promise in the following format:
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(mySuccessFunction);
promise.fail(myErrorFunction);
(and not with then() and catch() like was written in your code)
It's unnecessary to do Promise.resolve here, because the $.ajax call already returns a promise.
Try this:
function wikiAjax (searchURL) {
return $.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
}
});
}
$(".search-form").submit(function() {
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.done(function(data) {
alert(data);
}).fail(function(err) {
alert("The call has been rejected");
});
});
This is a working (and modified to show) plunker: https://plnkr.co/edit/qyc4Tu1waQO6EspomMYL?p=preview
I got an Ajax function that looks like this
function PersonAtlLawUpdate(personRef) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
$.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
}
In one function I need to run this twice like this:
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"));
PersonAtlLawUpdate(pRef);
The problem that can be is that in some cases doesn't work 100%. The dom doesnt update in one of the functions. And I think it is because the other one "overwrites" it.
So how do I make sure that the second "PersonAtlLawUpdate" runs after the first one completes? Doesnt seems good to put a delay on it. And is it a good solution to set async to false in the ajax call?
EDIT,
tride like this and placed a console.log in my success. But "all complete" will run first of them:
$.when(PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref")), PersonAtlLawUpdate(pRef)).then(function (){console.log("all complete")});
You can just use a callback function so that it executes right after the first one has executed:
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"), function(){
PersonAtlLawUpdate(pRef);
});
Or maybe you can rethink the problem, and come up with a solution that doesn't require calling the same function twice. Maybe you don't really need to do this.
I think what #Kyokasuigetsu suggests is you need to alter the PersonAtlLawUpdate method so that is accepts an optional second parameter: a callback function that need to be called in the success callback.
function PersonAtlLawUpdate(personRef, cbFunc) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
$.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
if (cbFunc != null)
cbFunc();
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
And than make the call as;
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"), function(){
PersonAtlLawUpdate(pRef);
});
Your example will work fine if you return your $.ajax calls from your PersonAtLawUpdate function.
$.when needs a reference to the ajax calls, so make sure you return the Deferred (the ajax call) from your functions
function PersonAtlLawUpdate(personRef) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
//SEE THE NEXT LINE
return $.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
}
Use:
$.when(PersonAtLawUpdate(ref1), PersonAtLawUpdate(ref2)).done(function(xhrRef1, xhrRef2) {
//do stuff w/ results from both calls
//if you return something from the server,
//the results will be available in xhrRef1[0]
//and xhrRef2[0], respectively (order they
//appear in the when(), not in the order they execute
});
im have a problem with method setTimeOut that call the function self and set a delay, the function should be called again and again after every request is done but it only runs once. It works without using backbone.js tho, don't know it doesnt work after integration with backbone.js. Any help is appreciated!
So this is a function in client that runs a GET request gets data from server, the request runs in a time interval(decided in the server), as soon as a data comes in, client gets it and the request runs again after.
getRequest:function() {
var XHR = $.ajax({
url: '/nextdocument',
type: 'GET',
async: true,
cache: false,
timeout: 11000,
success:function(data) {
var name = data.description;
var price = data.price;
console.log("read--> " + name + price);
setTimeout("this.getRequest", 1000);
if (data.ok == "true") {
data["ok"] = data.ok;
$.ajax(
{
url: "/customerdone",
data: JSON.stringify(data),
processData: false,
type: 'POST',
contentType: 'application/json'
}
)
}else{
//no document if no read in
console.log("error--> " + data.errorMessage)
}
}
})
return XHR;
}
The problem is that you're using "this" in your setTimeout call. You can't do this because "this" will be the global object when the timer executes the function you're trying to reference.
like others have suggested, you need to pass an actual function to your timer, not a string. then you can reference whatever function from whatever object you want.
probably, the function getRequest isn't being called. This is, as far as I think, because you are sending a string -- "this.getRequest" to the setTimeout function. As a rule of thumb, never pass string to this, pass functions. Although, it might be perfectly ok in some situations (i'd never recommend it anyway), here 'this' might be causing trouble. Use something like this:
getRequest:function() {
var fn = arguments.callee;
var XHR = $.ajax({
url: '/nextdocument',
type: 'GET',
async: true,
cache: false,
timeout: 11000,
success:function(data) {
var name = data.description;
var price = data.price;
console.log("read--> " + name + price);
setTimeout(fn, 1000);
if (data.ok == "true") {
data["ok"] = data.ok;
$.ajax(
{
url: "/customerdone",
data: JSON.stringify(data),
processData: false,
type: 'POST',
contentType: 'application/json'
}
)
}else{
//no document if no read in
console.log("error--> " + data.errorMessage)
}
}
})
return XHR;
}