Perform action at end of for loop javascript [duplicate] - javascript

This question already has answers here:
Wait until all jQuery Ajax requests are done?
(22 answers)
Closed 5 years ago.
I have been trying to redirect a page after the for loop has finished but it executes it before the for loop even if the code is outside the for loop. So am wondering if there is some way of executing code and redirecting to another page after the for loop is done in JavaScript. This is my code.
$('#submit').click(function(e) {
e.preventDefault();
var total = $('#total').val();
for (var i = 0; i < total; i++) {
if ($('#check_' + i).is(':checked')) {
// The string to be posted to the submit file
var dataString = 'month=' + month + '&year=' + year + '&patient_id=' + patient_id;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "pages/views/payroll/bulk_payroll_functions.php",
data: dataString,
cache: false,
success: function(result) {
alert("good");
}
});
}
}
alert("All members payrolls made");
window.location = ("index.php?lang=en&page=view_payroll");
})

The code is working as you're expecting - the AJAX requests are being made. However, because they are asynchronous, you are not guaranteed that they'll have finished before you redirect.
The cleanest way to do this would be to use the Promises which $.ajax returns.
You can then use $.when to redirect when all ajax requests are completed:
$('#submit').click( function(e) {
e.preventDefault();
// array to store the promises
var promises = [];
var total = $('#total').val();
for(var i = 0; i < total; i++){
if($('#check_' + i).is(':checked')){
// The string to be posted to the submit file
var dataString = 'month=' + month + '&year=' + year + '&patient_id=' + patient_id ;
// AJAX code to submit form.
promise = $.ajax({
type: "POST",
url: "pages/views/payroll/bulk_payroll_functions.php",
data: dataString,
cache: false,
success: function (result) {
alert("good");
}
});
// add ajax request to the promises
promises.push(promise);
}
}
// redirect when all promises have resolved
$.when(promises).then(function () {
alert("All members payrolls made");
window.location = ("index.php?lang=en&page=view_payroll");
});
});

Related

How do I stop my code from executing until an asynchronous piece of code has completed?

Today I've been struggling to get some JavaScript code working.
The goal of this code is to have all of the files names returned by the ajax function calls populated within the fileNameObj before the recordFormSubmission function is called.
async function uploadSubmissionFiles(files)
{
//Get an array for the names of each key of the files object
var filesKeys = Object.keys(files);
var fileSubmissionErrors = [];
var formElementPK = "";
//Create an object that keeps track of the file names that are saved to the server
var fileNamesObj = {};
//For each question where we uploaded files, call an ajax function
//where we transfer the files from the client to the server
var promiseToUploadFiles = () => {
return new Promise((resolve,reject) =>
{
for(let i = 0; i < filesKeys.length; i++)
{
formElementPK = filesKeys[i].match("(?<=fpk).*");
console.log(formElementPK);
if(files[filesKeys[i]]["type"] == "canvas")
{
var canvasElement = files[filesKeys[i]]["response"];
var canvasImageBase64 = canvasElement.toDataURL().split(';base64,')[1];
//Use ajax to upload the file to the server
$.ajax(
{
url: "./includes/ajaxColdfusion/fillout/submittedFileUpload.cfc?method=uploadSubmittedCanvasImage",
type: "POST",
data: canvasImageBase64,
enctype: 'multipart/form-data',
contentType: false,
processData: false
}
)
.then( function(response)
{
var responseElements = response.getElementsByTagName("string");
var resultMessage = responseElements[0].innerHTML;
console.log("File upload result for " + canvasElement.id + ": " + resultMessage);
if(resultMessage == "success")
{
//On success, responseElements[1] contains the name of the file that was saved to the server. We record it!
fileNamesObj[formElementPK] = responseElements[1].innerHTML;
}
else
{
//On failure, responseElements[1] contains the error message for what happened during the upload
fileSubmissionErrors.push(responseElements[1].innerHTML);
fileNamesObj[formElementPK] = "error.png";
}
console.log(fileNamesObj);
}
);
}
else if(files[filesKeys[i]]["type"] == "fileUpload")
{
var fileUploadForm = files[filesKeys[i]]["response"];
var formData = new FormData(fileUploadForm);
var fileFieldName = document.getElementById("question" + formElementPK + "FileUpload").getAttribute("name");
formData.append("fileFieldName", fileFieldName);
//Use ajax to upload the file to the server
$.ajax(
{
url: "./includes/ajaxColdfusion/fillout/submittedFileUpload.cfc?method=uploadSubmittedFile",
type: "POST",
data: formData,
enctype: 'multipart/form-data',
contentType: false,
processData: false
}
)
.then( function(response)
{
var responseElements = response.getElementsByTagName("string");
var resultMessage = responseElements[0].innerHTML;
console.log("File upload result for " + fileUploadForm.id + ": " + resultMessage);
if(resultMessage == "success")
{
//On success, responseElements[1] contains the name of the file that was saved to the server. We record it!
fileNamesObj[formElementPK] = responseElements[1].innerHTML;
}
else
{
//On failure, responseElements[1] contains the error message for what happened during the upload
fileSubmissionErrors.push(responseElements[1].innerHTML);
fileNamesObj[formElementPK] = "error.png";
}
console.log(fileNamesObj);
}
);
}
}
var retObj = {
"fileSubmissionErrors" : fileSubmissionErrors,
"fileNames" : fileNamesObj
}
console.log("Resolved the promise!");
resolve(retObj);
});
}
return await promiseToUploadFiles();
}
async function recordFormSubmission(data, formPK, fileNames)
{
var JSONData = JSON.stringify(data);
var JSONFileNames = JSON.stringify(fileNames);
var submissionErrors = [];
console.log("Filenames at trigger of record form submission: ", fileNames);
console.log("Now waiting 2 seconds with await new Promise(r => setTimeout(r, 2000));");
await new Promise(r => setTimeout(r, 2000));
console.log("Fileanmes after 2 seconds of triggering record form submission", fileNames);
$.ajax(
{
url: "./includes/ajaxColdfusion/fillout/recordFormSubmission.cfc?method=recordFormSubmission",
type: "POST",
data: "JSONData=" + JSONData + "&formPK=" + formPK + "&JSONFileNames=" + JSONFileNames,
enctype: 'multipart/form-data',
cache : false
}
).
done(function(response)
{
//If successful...
console.log("Record form submission successful:" + response.getElementsByTagName("string")[0].innerHTML);
}
).
fail(function(response)
{
//If not successful...
console.log("Record form submission failed");
submissionErrors = [response.getElementsByTagName("string")[1]];
}
);
return submissionErrors;
}
uploadSubmissionFiles(filesToUpload.then( function(fromUploadSubmissionFiles)
{
var fileSubmissionErrors =
fromUploadSubmissionFiles["fileSubmissionErrors"]
var fileNames = fromUploadSubmissionFiles["fileNames"];
//Query the database to save our form data to the database
var formDataSubmissionErrors = recordFormSubmission(dataToRecord, formPK, fileNames);
}
Above are all the important parts of this code. As it stands right now though, recordFormSubmission() gets called and executes before the fileNamesObj variable is populated with file names that are returned from the ajax function. This must mean that the code is not waiting on the ajax to finish executing before continuing with execution, even though a promise has been implemented.
I suppose my question here is, what am I doing wrong if I want the JavaScript code to wait until all of the ajax functions are completed before calling recordFormSubmission()?
I could probably think of a polling solution here, but I'd like to think that there's a way to solve this with promises or better practice.
This is the result of running the modified code to return an awaited promise. It also shows how the ajax functions return and the filenames are obtained in the window of time between waiting two seconds and when the critical point where the filenames must exist occurs.
The solution to this was found within an answer to another question: https://stackoverflow.com/a/66747114/16511184
Credit to #Heretic-Monkey for providing it.
The solution: put an await in front of each ajax() function call. Do NOT encapsulate anything within a promise.
I'm new to the concept of Promises in Javascript, so I unknowingly made an error of encapsulating promises inside of eachother. It's very important to note that the jquery ajax() function returns a promise. In my problem, I was triggering asynchronous code that I was not using await for. Instead I used await for a function that contained an ajax() function. The await wouldn't wait very long at all because all the code was doing was triggering the ajax() function and leaving, not waiting for it to finish (the very crux of what I wanted to occur).
Here's a good analogy:
You're going to the supermarket with your friend. You tell your friend to split up from you and grab a carton of eggs. You wait for them, and once they come back from grabbing the eggs you'll both go to the checkout counter together.
Effectively, the problem I had was I decided to wait until I was done telling my friend to get eggs to go to the checkout counter. I needed to wait for my friend to SPECIFICALLY get the eggs.
try this.
async function uploadSubmissionFiles(files)
{
...
var promiseToUploadFiles = () => {
return new Promise((resolve,reject) =>
{
$.ajax(
{
url: "./includes/ajaxColdfusion/fillout/submittedFileUpload.cfc?method=uploadSubmittedFile",
type: "POST",
data: formData,
enctype: 'multipart/form-data',
contentType: false,
processData: false
}
)
.then( function(response)
{
var responseElements = response.getElementsByTagName("string");
var resultMessage = responseElements[0].innerHTML;
console.log("File upload result for " + fileUploadForm.id + ": " + resultMessage);
if(resultMessage == "success")
{
//On success, responseElements[1] contains the name of the file that was saved to the server. We record it!
fileNamesObj[formElementPK] = responseElements[1].innerHTML;
}
else
{
//On failure, responseElements[1] contains the error message for what happened during the upload
fileSubmissionErrors.push(responseElements[1].innerHTML);
fileNamesObj[formElementPK] = "error.png";
}
resolve(fileNamesObj);
}
)
.catch(function(e) {
reject(e)
});
}
}
return await promiseToUploadFiles();
...
}
await uploadSubmissionFiles(filesToUpload).then( function(fileNameObj)
{
recordFormSubmission(..., fileNameObj)
}).catch(function(e) {
console.error(e);
});
It is necessary to wrap your promise in a function and wait for its completion after the call. When you have assigned a promise to a simple variable, the request immediately starts working and the code runs on without waiting for completion

loop chained async ajax calls with promise and returns between functions

I am loading results in batches and looking for a solution that will prevent the screen from freezing until all my ajax calls have returned. Someone recommended using async promises (is that the correct solution?) but I don't understand how the syntax works to pass parameters between the chained calls.
It's the equivalent of this looped chain of many ajax calls except I need all calls to depend on the result from the previous call (in this example the loops for url1 all fire simultaneously which is not what I want). The run should end when the returned boolean "proceed" (from any of the ajax calls) is false, not when the last loop and url have been reached.
for (let i = 0; i < numLoops; i++) {
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: i}),
success: function(response) {
var result = JSON.parse(response);
if(result['proceed']){
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
if(result['proceed']){ ... and so on
I am trying to use jquery .when .then promises with these functions:
function First(loop, proceed, updated){
if(proceed)
{
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: loop}),
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Second(proceed, updated){
if(proceed)
{
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Third(proceed, updated){
if(proceed)
{
$.ajax({
url: url3,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
I'm having a hard time figuring out how to chain them so that the return from previous function is passed to the next function.
This incorrect syntax describes what I'm trying to do:
var proceed=true;
for (let i = 0; i < numLoops; i++) {
$.when(First(i, proceed, updated); function updated(content) {var proceed=contents;} )
.then(Second(proceed, updated); function updated(content) {var proceed=contents;})
.then(Third(proceed, updated); function updated(content) {var proceed=contents;})
}
How to pass updated proceed from First to Second?
How to pass updated proceed from Third to First at end of each loop?
I'm not super versed with javacript and would be most grateful for pointers. Thanks!
First, convert the $.ajax calls into real Promise objects, as described in this thread:
function asyncAjax(options){
return new Promise(function(resolve, reject) {
options.success = resolve;
options.error = reject;
$.ajax(options);
});
}
Alternatively, use the Fetch API, which supports promises by default.
Then use an async function to make the requests:
for (let i = 0; i < numLoops; i++) {
let response = await asyncAjax({
url: url1,
type: "POST",
data: jQuery.param({loop: i})
});
let result = JSON.parse(response);
if (result['proceed']) {
response = await asyncAjax({ url: url2 });
result = JSON.parse(response);
...
}
}

Use of async on successive AJAX calls

Question here about use of successive AJAX calls and async. Its a bit messed here because of how the data is set up. I need to return listings, but the sever only returns 10 per query, and the only way to determine the total number of listings is a separate query with the boolean returnTotal as true instead of false. This returns the number of listings only, and not the listing results themselves. However, if I run the calls synchronously, the variable startItem (which increments on each loop to load data starting at the next block of listings) doesn't seem to populate before the next call finishes, and results get duplicated. Any way to avoid running both as async? Apologies if my code is batshit ridiculous, as I'm relatively new to jquery.
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem=0&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=true",
dataType: "html",
async: false,
success: function(data) {
data=convert(data);
$(data).find('Listing').each(function(){
$(this).find('total').each(function(){
totalList = $(this).text();
totalList = parseInt(totalList);
totalPages = totalList/10;
});
});
},
});
for (i = 0; i < totalPages; i++){
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem="+startItem+"&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=false",
dataType: "html",
success: function(data) {
data=convert(data);
$(data).find('Listing').each(function(){
results_xml.push($(this));
});
result_index=0;
result_image_counter=1;
startItem = startItem + 10;
popResults();
},
});
}
The problem here is that you do not increment startItem until you receive a response. Your code is probably making multiple requests with startItem === 1 before the first response is even received, and so you will get some really weird behavior (probably will get duplicate responses, and you will only get the first few pages of data).
Avoid using synchronous calls because they will tie up other resources (like javascript).
In this case if you want to insure that you get the data in order, you can make it a serial chain of AJAX calls.
To get serial behavior and enjoy the benefits of AJAX, instead of using a loop make your callback function do the next AJAX request after incrementing startItem.
This is easier if you organize your code into functions. To wit:
function GetData()
{
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem="+startItem+"&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=false",
dataType: "html",
success: GetData_Callback
});
}
function GetData_Callback(data)
{
data=convert(data);
$(data).find('Listing').each(function(){
results_xml.push($(this));
});
result_index=0;
result_image_counter=1;
startItem += 10; // increment startItem
popResults();
if (startItem / 10 < totalPages)
{
GetData(); // get next "page" of data
}
}
var startItem = 1; // global variable will be mutated by GetData_Callback
GetData(); // get first "page" of data
To do this in parallel typically requires management of the parallel responses (you can use semaphores, etc.). For example (psuedo code) you could do something like this:
var pages = [];
var totalPages = GetTotalPages(); // request via ajax like you mentioned (function not shown)
var pagesLoaded = 0;
for(var i = 0; i < totalPages; i++)
{
GetData(pageIdx);
}
function GetData(pageIdx)
{
$.ajax({ ..., success: function(data){GetData_Callback(pageIdx,data);}});
}
function GetData_Callback(pageIdx, data)
{
pages[pageIdx] = data; // assign this specific page of data
pagesLoaded++;
if (pagesLoaded === totalPages)
{
// fully loaded; trigger event or call function to render, etc.
}
}
Do you just mean without the async: false?
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem=0&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=true",
dataType: "html",
success: function(data) {
console.log('test1'); // first response ok
data=convert(data);
$(data).find('Listing').each(function(){
$(this).find('total').each(function(){
totalList = $(this).text();
totalList = parseInt(totalList);
totalPages = totalList/10;
});
});
var startItem=0;
console.log(totalPages); // total page should be equal too "loop" logged
for (i = 0; i < totalPages; i++){
console.log('loop'); // enter the loop
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem="+startItem+"&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=false",
dataType: "html",
success: function(data) {
console.log('test2'); // number of test 2 = nb of loop = totalPages
data=convert(data);
$(data).find('Listing').each(function(){
results_xml.push($(this));
});
result_index=0;
result_image_counter=1;
startItem = startItem + 10;
popResults();
},
});
}
},
});
The problem here is that you do not increment startItem until you receive a response. Your code is probably making multiple requests with startItem === 1 before the first response is even received, and so you will get some really weird behavior (probably will get duplicate responses, and you will only get the first few pages of data).
Try this instead. It still uses your loop but it increments startItem in the loop before the next request is made to insure that all pages of data are requested.
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem=0&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=true",
dataType: "html",
async: false,
success: function(data) {
data=convert(data);
$(data).find('Listing').each(function(){
$(this).find('total').each(function(){
totalList = $(this).text();
totalList = parseInt(totalList);
totalPages = totalList/10;
});
});
},
});
var startItem = 1;
for (i = 0; i < totalPages; i++){
$.ajax({
type: "POST",
url:server url here,
data:"creativeID=test&CompanyId=BHSR&StartItem="+startItem+"&streetlocation="+choiceTown+"&Location="+sectCode+"&PriceMin="+choiceMin+"&PriceMax="+choiceMax+"&ListingType="+checkRB+"&OpenHouse=false&NewDev=false&AuthenticationId=id&ReturnTotal=false",
dataType: "html",
success: function(data) {
data=convert(data);
$(data).find('Listing').each(function(){
results_xml.push($(this));
});
result_index=0;
result_image_counter=1;
popResults();
},
});
// increment start item BEFORE the next request, not in the response
startItem += 10; // now the next request will be for 11, 21, 31, 41, etc...
}
You may want to get familiar with your javascript debugger to see the behavior for yourself.

jquery form send ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have the following validate script to run before the form is submitted:
function validateMyForm(){
var numberTo = $('.to').length
$('.to').each(function(){
var product_id = $(this).closest('tr').find('input').get(0).id;
var todate = $(this).val();
var from = $(this).prev().prev().val();
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/ajax_change_date',
dataType: 'json',
data: {
id: product_id,
todate: todate,
from: from
},
success: function (data) {
numberTo--;
}
});
});
while(numberTo != 0){
}
return true;
}
However when i run this i get a message box in firefox saying its waiting for the script to complete.
How do i avoid that while still keeping the ajax?
Using:
while(numberTo != 0){
}
You create infinity loop and your scrip stop executing. This is why you get this error on Firefox.
You will need to have callback to check numberTo variable.
For example:
function validateMyForm(){
var numberTo = $('.to').length;
function checkNumberTo() {
if( numberTo === 0 ) {
alert( 'AJAX Completed' );
// here you should include your code to manually submit the form
}
}
$('.to').each(function(){
var product_id = $(this).closest('tr').find('input').get(0).id;
var todate = $(this).val();
var from = $(this).prev().prev().val();
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/ajax_change_date',
dataType: 'json',
data: {
id: product_id,
todate: todate,
from: from
},
success: function (data) {
numberTo--;
checkNumberTo()
}
});
});
return false;
}
If you want a more elegant solution you might want to try a promise library.
Here is an essay https://gist.github.com/domenic/3889970 that presents the downside of using callbacks and the solution to it - Promises. The essay is long, but it is worthy to read.
To get to how this new concept applies to you, you should try researching Promise composition, here is the first article I could find on Google on this:
http://strongloop.com/strongblog/how-to-compose-node-js-promises-with-q/.
var x = 10; var promise1 = Q($.ajax(...)).then(function () {
x = 20; });
var promise2 = Q($.ajax(...)) .then(function () {
x = 30; });
var groupPromise = Q.all([ promise1(), promise2() ])
groupPromise.then(function (results) { }, console.error) // Kris Kowal's example
Promises l and 2 execute in paralel and one does not know which will be fulfilled first.
Here are 2 relevant promise libraries:
https://github.com/kriskowal/q
https://github.com/cujojs/when

ajax calls and append, cannot select appended content or do anything

I've two problems with this code.
1 $(container + ' meta[data-level="' + level + '"]').length == 0 is always zero
I know this because I create extra call create_views(1); which should not get added, but it gets appended anyhow.
2 dpUniSlider doesn't work as it doesn't see li created via ajax call. If I move it into success message it works fine, but outside function does not. Problem is if I include it inside ajax success it will get called several times as it is under a loop
//Show levels using ajax, before slider is activated
function create_views(level) {
$.ajax({
url: "actions.php",
type: "GET",
data: "show_level=" + level,
cache: false,
success: function (data) {
var view = '<li data-level="' + level + '">' + data + '</li>';
var container = ".slides_container";
if ($(container + ' meta[data-level="' + level + '"]').length == 0) {
$(container).append(view);
} else { //check if element exists, if yes overwrite it.
//$(container + ' meta[data-level="' + level + '"]').replaceWith(view);
alert("Exists");
}
}
});
}
//Loop through all levels and display views
//level count can be rewritten to come from DB and not be hardcoded like now
var levels = 2;
for (var i = 1; i <= levels; i++) {
create_views(i);
} // for loop
create_views(1); //test, delete this
//Activate slide
var unislider = $(".slides_container").dpUniSlider({
//loop: false,
draggable: false
});
For handling multiple parallel asynchronous ajax calls where you want to perform something after they have all completed, you could keep a counter and check in the success callback to see when the last ajax call has succeeded.
It would look like this:
$(function() {
var TOTAL_TASKS = 2,
completedTasks = 0;
function performAjaxTask(taskNumber) {
$.ajax({
url: url,
type: 'GET',
data: data,
cache: false,
success: function(data) {
// Process the data
completedTasks++;
if (completedTasks == TOTAL_TASKS) {
// Perform actions that need to wait until all
// ajax calls have returned successfully.
}
}
});
}
for (var i = 1; i <= TOTAL_TASKS; i++) {
performAjaxTask(i);
}
});
I believe you can use jQuery deferred objects for handling the multiple parallel asynchronous ajax calls where you want to perform something after they have all completed successfully.
Try this:
$(function() {
var LEVELS = 2,
$container = $('.slides_container'),
deferreds = []; // This will hold the deferred objects.
// This function returns a deferred object.
function getViewAndReturnDeffered(level) {
return $.ajax({
url: 'actions.php',
type: 'GET',
data: 'show_level=' + level,
cache: false,
success: function(data) {
var $currentView = $container.find('[data-level="' + level + '"]'),
$newView = '<li data-level="' + level + '">' + data + '</li>';
if ($currentView.length > 0) {
$currentView.replaceWith($newView);
} else
$container.append($newView);
}
}
});
}
for (var i = 1; i <= LEVELS; i++) {
// Put the deferred objects in the array.
deferreds.push(getViewAndReturnDeffered(i));
}
// The function passed to `.done()` will execute when all the deferred
// objects have completed successfully.
$.when.apply($, deferreds).done(function() {
var unislider = $container.dpUniSlider({
//loop: false,
draggable: false
});
});
});
Do you have a <meta></meta> inside .container? Probably not. Use
$(container + ' li[data-level="' + level + '"]')

Categories

Resources