I'm trying to display two progress bars for multiple ajax requests. One progress bar reaches 100% each time one of my 18 ajax requests is complete and another reaches 100% when all 18 requests are complete. The first bar works great and is implemented in my ajax success callback. I'm having trouble triggering my second bar because it seems I need a second success callback...
Here is the code for my first ajax requests. It gets called 18 times because that is how many items are in my Config object.
for (var propt in Config) {
var db = '...';
var user = '...';
var pword = '...';
var func = '...';
var dat = {"...": propt };
var url = "https://...";
var callData = jQuery.extend({"Db": db, "User": user, "Password": pword, "Function": func}, dat);
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(callData),
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(event){
var percentComplete = (event.loaded / event.total)*100;
//Do something with download progress
tableProgressBar(percentComplete);
}, false);
return xhr;
},
success: successHandlerRunTest1,
error: errorHandlerRunTest1,
dataType: "json"
});
$('#jsonMsg1').html('Running...');
$('#jsonRslt1').html(' ');
}
I would also like to fire this success function simultaneously.
success : function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
},
Unfortunately I don't believe I can call the second success function from within the first success function because the first receives special parameters containing JSON data.
I've tried something like...
success : function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
successHandlerRunTest1(data);
},
...but this doesn't work because the "data" object that my successHandlerRunTest1(data) receives is empty.
Is there a way to perform two success callbacks per ajax request?
Don't use the success parameter.
Use the done method to attach callbacks, as it returns the promise for chaining you can call it multiple times:
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(callData),
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(event){
var percentComplete = (event.loaded / event.total)*100;
tableProgressBar(percentComplete);
}, false);
return xhr;
},
dataType: "json"
})
.done(successHandlerRunTest1)
.fail(errorHandlerRunTest1)
.done(function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
});
You could simply pass both callbacks inside the original success callback. Then use .apply to pass the same arguments as the success callback was originally called with.
success: function()
{
callbackOne.apply(this, arguments);
callbackTwo.apply(this, arguments);
}
see .apply() method.
see arguments property.
Also as a side note never ever put database usernames and passwords in javascript. Since anybody can access it.
Try (this pattern) , utilizing deferred.always()
html
<progress id="p1" max="1" value="0"></progress>
<progress id="p2" max="17" value="0"></progress>
<span id="jsonMsg1"></span>
<span id="progress-bar"></span>
js
$(function () {
var count = null;
var Config = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
for (var propt in Config) {
var db = '...';
var user = '...';
var pword = '...';
var func = '...';
var dat = {
"...": propt
};
var url = "/echo/json/";
var callData = jQuery.extend({
"Db": db,
"User": user,
"Password": pword,
"Function": func
}, dat);
var successHandlerRunTest1 = function (data, textStatus, jqxhr) {
// Do something with download progress
$("#p1").val(1);
};
var response = [];
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: {
json: JSON.stringify(callData)
},
beforeSend: function (jqxhr, setiings) {
jqxhr.count = ++count;
// Do something with download progress
$("#p1").val(0);
},
/*
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(event){
var percentComplete = (event.loaded / event.total)*100;
//Do something with download progress
tableProgressBar(percentComplete);
}, false);
return xhr;
},
*/
success: successHandlerRunTest1,
error: function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
},
dataType: "json"
})
.always(function (data, textStatus, jqxhr) {
$('#jsonMsg1').html('Running...');
response[response.length] = data;
$("#progress-bar")
.text(Number(data["..."])
+ ' of '
+ Config.length + ' tables are done');
$("#p2").val(Number(data["..."]));
// Do something with download progress
if (data["..."] === "17" && jqxhr.count === 18) {
console.log(data["..."]);
$('#jsonMsg1').html('Done...');
$("#progress-bar")
.text(Number(data["..."]) + 1
+ ' of '
+ Config.length + ' tables are done');
};
});
// $('#jsonRslt1').html(' ');
};
});
jsfiddle http://jsfiddle.net/guest271314/z6DzF/4/
See
http://api.jquery.com/jQuery.ajax/#jqXHR
http://api.jquery.com/deferred.always/
Related
I have some functions that make some ajax calls.In order to execute everything the way is needed, these requests must by set with async: false.Everything is ok with the ajax call. My problem is that I need a div (a simple css loader) to be shown before send the request and hide after it, but it is not showing.This is my function:
$("#btn1").on('click', function(){
// Apparently it does not executes this
$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});
var modal = document.getElementById('Modal1');
modal.style.display = "none";
return false;
});
My doSomeStuff() function that makes the requests:
function doSomeStuff(callback){
//...
for (var i = 0; i < ids.length; i++) {
var Id = ids[i][0];
var ch = ids[i][1];
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + ch;
$.ajax({
cache: "false",
async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
toastr.error('error' );
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}
});
}
callback({ok: true});
}
Any idea on how can I handle this? I am really new with async stuff.
Solved this by removing async and changing the mthod in my server to receive an array as a parameter. The final script:
$("#btn1").on('click', function(){
//$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});
});
My doSomeStuff() function that makes the requests:
function doSomeStuff(callback){
//...
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + encodeURIComponent(JSON.stringify(jsonArray));
$.ajax({
cache: "false",
//async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
callback({ok: false});
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}, complete: function(){ //hide the loader after complete
$('.container-loader').hide();
var modal = document.getElementById('Modal1');
modal.style.display = "none";
}
});
}
I have a problem synchronizing calls using Rest Api and JavaScript Object Model.
I'm currently working with Client Side Rendering to customize a view for a Document Library and add some functionalities in this custom UI.
I have a small collection of id's, and I'm looping through this collection and make some ajax calls with each of this items.
The results of this operation is to perform some tasks and to update my UI when all these operations are completed to refresh my UI and display some icons.
What I expect is to have 3 icons displayed only for my three first items.
The problem is that sometimes it displays all the icons, sometimes the two first... randomly.
I know that there is some problems with the synchronization of my executeQueryAsync calls, I've learned about jQuery Deferred object, I've tried to use them but without results.
Below you'll find screenshots of what I expect.
Expected :
https://onedrive.live.com/redir?resid=E2C3CC814469DA54!3070&authkey=!AEf_C0XGDwfuFRY&v=3&ithint=photo%2cpng
What would be the good way of using deferred ? Could anyone help ?
Thanks a lot
Elhmido
This is my main function for overriding the display :
(function () {
var accordionContext = {};
accordionContext.Templates = {};
// Be careful when add the header for the template, because it's will break the default list view render
accordionContext.Templates.Item = itemTemplate;
// Add OnPostRender event handler to add accordion click events and style
accordionContext.OnPreRender = [];
accordionContext.OnPreRender.push(function () {
$(function () {
IsCurrentUserMemberOfGroup("TEST Owners");
**$.when(IsUserApprover(arrayOfIDS).done(function () {
displayIcons();
}));**
});
});
accordionContext.OnPostRender = [];
accordionContext.OnPostRender.push(function () {
$(function () {
accordionOnPostRender();
fixColumns();
audit.relativeUrl = _spPageContextInfo.webAbsoluteUrl;
});
});
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(accordionContext);
})();
The function where I have the problem,
function IsUserApprover(auditTab) {
var dfd = $.Deferred();
audit.tabIcons = new Array();
for (var i = 0; i < auditTab.length; i++) {
var uri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/Lists/GetByTitle('Audit')/items?$select=UserID&$filter=ID eq " + auditTab[i] + "";
var call = $.ajax({
url: uri,
type: "GET",
dataType: "JSON",
async: false,
headers: {
"Accept": "application/json;odata=verbose"
}
});
call.done(function (data, status, jqxhr) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var userId = data.d.results[0].UserID;
var context = SP.ClientContext.get_current();
var auditor = context.get_web().ensureUser(userId);
context.load(auditor);
//I think the problem is here because I don't know how to handle this call
context.executeQueryAsync(userLoaded, userFailed);
function userLoaded() {
var auditorId = auditor.get_id();
checkAuditorValidator(auditorId);
dfd.resolve();
}
function userFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
});
});
call.fail(function (jqxhr, status, error) {
alert(JSON.stringify(error))
dfd.reject();
});
}
return dfd.promise();
}
function checkAuditorValidator(auditorId) {
var uri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/Lists/GetByTitle('SecurityMgmt')/items?" +
"$select=Auditeur/ID,Validateur/ID" +
"&$expand=Auditeur/ID,Validateur/ID" +
"&$filter=(Auditeur/ID eq '" + auditorId + "') and (Validateur/ID eq '" + _spPageContextInfo.userId + "')";
var call = $.ajax({
url: uri,
type: "GET",
dataType: "JSON",
async: false,
headers: {
"Accept": "application/json;odata=verbose"
}
});
call.done(function (data, status, jqxhr) {
if (data.d.results.length > 0) {
if (audit.UserAdmin) {
audit.tabIcons.push(true);
}
}
else {
audit.tabIcons.push(false);
}
});
call.fail(function (jqxhr, status, error) {
alert(JSON.stringify(error))
});
}
Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
You should avoid synchronous ajax calls...
I had the same problem and solved by adding an id during the custom rendering of the fields (items), on the postrender call my service asynchronously and according the result edit the OnPreRender page using the previously added ids.
I also did some hacks...e.g overriding the standard function RenderItemTemplate. Yes I know, it's not very clean but it works like a charm.
Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.
After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps
function pdfToImgExec(file, IsfirstLogging, folder, round) {
alert(file);
var postString = file + '&' + IsfirstLogging + '&' + folder + '&' + round;
var errorMsg = (folder == 'Incoming' ? '<p>error in incoming folder</p>' : '<p>error in other folder</p>');
$.ajax({
type: "POST",
cache: false,
async: false,
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
alert(file + 'a');
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
if(data == '1') {
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
} else if(round < 4) {
$('#pdfToImgResult').html('<p>Fail to convert , retry ' + round + ' round <img src="loading.gif" height="20" width="20"/></p>');
round++;
pdfToImgExec(file, 'false', folder, round);
} else {
folder == 'Incoming' ? tempFailIncomingFiles.push(file) : tempFailResultFiles.push(file);
}
},
error: function (x, t, m) {
$('#pdfToImgResult').html(errorMsg);
alert(t);
releaseBtn();
}
});
}
The problem of this ajax call is I can alert the (file + 'a') in the beforeSend function , but the
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
is not working, it will not display anything but only jumped to the
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
after the ajax call is finished.
Is it due to async:false? How to fix the problem ? thanks.
It's because you're using async: false,, so the function blocks until the request is complete, preventing a redraw until everything is done.
You seem to be all set up with callbacks, so there doesn't seem to be any reason to make a blocking xhr request. Just remove the async: false,, and you should be all set.
Here's a quick example of how to deal with asynchronous code. I've removed most of your code to keep it brief.
// --------------------------------new parameter-------------v
function pdfToImgExec(file, IsfirstLogging, folder, round, callback) {
// your code...
$.ajax({
type: "POST",
cache: false,
// async: false, // Remove this line!
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
// your code...
// Invoke the callback, passing it the data if needed
callback(data)
},
error: function (x, t, m) {
// your code;
}
});
}
When you call pdftoImgExec, pass a function as the last parameter that will be invoked when the response is complete. That function is where your code resumes.
pdfToImgExec(..., ..., ..., ..., function(data) {
// resume your code here.
alert(data);
})