I know the there is a lot of questions on this topic, but I really couldn't find anything what fits to my case. I defined this function in javascript:
self.ajax = function(uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function(jqXHR) {
console.log("ajax error" + jqXHR.status);
}
};
return $.ajax(request);
}
And I call this function later like that:
self.ajax(self.tasksGetUri, 'POST', self.jsonRequest).done(function(data) {
for (var i = 0; i < data.tasks.length; i++) {
self.tasks.push({
user_id: ko.observable(data.tasks[i].user_id),
task_id: ko.observable(data.tasks[i].task_id),
done: ko.observable(data.tasks[i].done)
});
}
$(document).ready(function() {
for (var i = 0; i < self.tasks().length; i++) {
task = $("#" + self.tasks()[i].task_id());
if (task.length) {
task.slideUp(400);
task.parent().find(".unFinishedTask").hide();
task.parent().addClass("finished");
task.parent().find(".showTask").show();
}
}
});
});
Well, I want this calling of the function to be performed periodically together with return 'done()' function. I know the there is function setInterval(), but I don't know if it fits in my case. Can somebody recommend me some other solution ?
Thanks in advance for any help.
Related
So I have a function that executes an ajax call in a for loop. I need to callback another function when the entire for loop is done. Since the ajax calls are running asynchronously, I'm not able to call the next function once the for loop is done.
Here's my code:
for(let i=0; i< industryArray.length; i++){
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
},
error: function (data) {
}
})
}
// Need to call myfunction() here
myfunction() is being called even before the ajax calls are executed. Thanks!
Set ajax asyc state false then it will work
this is a sample example to set ajax asyc false
$.ajax({
url : "/submit/checkuser/",
type : "get",
async: false,
success : function(userStatus) {
if (userStatus == 'Disabled') { // check if user if disabled
} else if (userStatus == 'Deleted') { // check if user if deleted
} else {
};
},
error: function() {
connectionError();
}
});
Right now it wait for the function to get executed and moved to the next line
var pendingRequests=0;
for(let i=0; i< industryArray.length; i++){
if (condition) {
pendingRequests++;
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
pendingRequests--;
if(pendingRequests===0) {
otherFunction()
}
},
error: function (data) {
doSomethingWithError(data)
}
})
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have an ajax call, that based on the return, calls another ajax call by effecting its url parameter, the url being modified by the return of the first. These two calls are related, because the first feeds the url parameter of the second, and its output is appended to a global variable which is used to generate a final set of HTML, subsequently appended in the first call. As a simplified example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';
$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandler(data);
},
error: function (data) {
}
});
function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someHtml = results[i]["someHtml"];
masterHtml = masterHtml + someHtml;
var nextThingUrl = results[i]["nextThingUrl"];
// now go get the other HTML, and append it to the masterHtml,
//this is a series of child elements to the someHtml variable above
$.ajax({
url: "http://thisisanexample/+ " + nextThingUrl,
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandlerChildren(data);
},
error: function (data) {
}
});
jQuery('#magictime').append(masterHtml);
}
}
function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someMoreHtml = results[i]["someMoreHtml"];
masterHtml = masterHtml + someMoreHtml;
}
}
My problem is the first ajax call always completes all the way before the second call is issued so I get the first set of HTML, while the second call provides some HTML I need. This messes up the order of operations. What am I missing? TIA!!!
The option for async is spelled wrong, correct is:
async: false
Looks like you're appending your data too early. Move jQuery('#magictime').append(masterHtml); to function successHandlerChildren(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';
$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandler(data);
},
error: function (data) {
}
});
function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someHtml = results[i]["someHtml"];
masterHtml = masterHtml + someHtml;
var nextThingUrl = results[i]["nextThingUrl"];
// now go get the other HTML, and append it to the masterHtml,
//this is a series of child elements to the someHtml variable above
$.ajax({
url: "http://thisisanexample/+ " + nextThingUrl,
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandlerChildren(data);
},
error: function (data) {
}
});
}
}
function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someMoreHtml = results[i]["someMoreHtml"];
masterHtml = masterHtml + someMoreHtml;
}
jQuery('#magictime').append(masterHtml);
}
The following code is not storing values in the Array
var checkListIdForEmail= new Array();
var checkListNameforEmail;
function getCheckListIdAndName() {
$.ajax({
type: "GET",
url: 'URL/' + 12464,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
for (var i=0; i< result.length;i++) {
$('#checkListIdForEmail').val(result.checklistDetailId[i]);
}
// alert("Success");
},
error: function (error) {
alert("Errror while getting header values");
}
});
}
Can anyone please let me know what needs to store all data in an array..
Thank You
I would suggest on your success callback, do this instead.
success: function (result) {
checkListIdForEmail = result;
},
since result is already an array
Maybe this is what you want to store to the checkListIdForEmail array:
for (var i=0; i< result.length;i++) {
checkListIdForEmail[i] = result[i].checklistDetailId;
}
$('#checkListIdForEmail').val(checkListIdForEmail);
I am loading 2 XML documents that both run functions on success, although the function for the 2nd XML document is dependant on the 1st being complete.
If I have async:true:
1st XML
function XmlDataTypes() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
2nd XML
function XmlAmenityData() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlAmenityData?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//store this info in markerArray in dataTypeArray
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
The XML data can loaded in a random order so the function for the second document will error if the 1st hasn't completed.
If I set:
async: false
It works correctly but I get a warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Is there a way around this without using:
async: false
Since the 2nd xml is dependent on the 1st, you can define a callback on success.
Also since ajax is async, you must assign the result when the callback is called. You can define a variable ourside of your function (in this case an array) and put the data there.
var result = [];
function XmlDataTypes(url, accountId, callback) {
var scriptUrl = url + accountId;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
// do something
result.push(data);
if(typeof callback == 'function') {
callback();
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
function doSomething() {
// Do something to store this info in markerArray in dataTypeArray
// XmlAmenityData is in results var.
}
And you can use it like so
var _callback = XmlDataTypes("http://domain.com/xml/test.XmlAmenityData?AccountId=", "1234", doSomething);
XmlDataTypes("http://domain.com/xml/test.XmlDataTypes?AccountId=", "1234", _callback);
EDIT: Updated script based on given scenario.
You could try to return the $.ajax as a promise:
function XmlDataTypes() {
// note domain.com was changes to example.com - this should be changed back
var scriptUrl = "http://example.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
return $.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
Then calling them in sequence :
XmlDataTypes.done(XmlAmenityData);
Here is some more documentation :
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
If I have a function like this, i pass in a variable of movieid.
function getFilmDetails(movieid) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
async: false,
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
filmDetails = result;
}
});
return filmDetails;
}
I'm calling over 100 films details through this function and as you can imagine, it takes forever to load the page by doing it this way. I need to easily access the values in the JSON for each film. For example:
alert(getFilmDetails(12345).description);
alert(getFilmDetails(65432).popularity);
alert(getFilmDetails(12345).tagline);
Is there a better way to do this?
// receive a callback------------v
function getFilmDetails(movieid, callback) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
// async: false, // YUCK! Commented out
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
callback(result) // invoke your callback
});
return filmDetails;
}
// make a callback
function workWithData(data) {
alert(data.description);
}
// pass the callback
getFilmDetails(12345, workWithData);