I have a function which is as follows:
//Calling the Function with one Parameter
responses(baseURL);
//Function Definition
function responses(baseURL) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArrayT1.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 1");
console.log(taxArrayT1.length);
}
})
}
Now I tend to repeat myself because when I hit different services with the same function. I know how to pass the base URL as a parameter. Also there is an array like in this example, taxArrayT1. This array changes every time a different input is used, like taxArrayT2. It would be great if you have suggestions on how to accomplish. It would be of great help.
If I understand correctly what you are trying to do then you can just add the array as a second parameter. Like this:
function responses(baseURL, taxArray) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArray.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArray.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 1");
console.log(taxArray.length);
}
})
}
And the service calls will look like this:
responses(url1, taxArrayT1);
responses(url2, taxArrayT1);
Related
I am working on a flask application and there is this javascript function associated with a form
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
The addCatalogFilters() function is also an ajax call. Both these calls change some variables in the python side of things. What I want to know is if the first ajax call (in addCatalogFilters), is guaranteed to execute and return before the second one. I am ending up with weird results that appear to be race conditions based on the order the ajax calls execute. Is this possible with code structured like this? Also if so, how can I fix it?
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
$.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can ensure with success function of ajax. First call a ajax (let's say ajax1) then call another ajax call within the success function of first ajax call (ajax1 success function).
addCatalogFilters(currentCatalog)
{
$.ajax({
type: 'POST',
url: "/the-post-usl",
success:function(response){
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
});
})
}
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
}
It may not be the optimum way. But guarantee one ajax call is complete before calling another.
You could try using async/await like this:
async function applyQueries() {
if(currentCatalog !== ''){
const filtersAdded = await addCatalogFilters(currentCatalog);
}
// Perform AJAX call
}
By usinc async/await, your code will wait until the addCatalogFilters() function has resolved. However, for this to work, the addCatalogFilters() function should be async with a return value. Something like this:
async function addCatalogFilters(catalog){
// Ajax call
$.ajax({
type: 'POST',
url: "foo",
contentType: "application/json",
success:function(response){
return true
})
}
Depending on how applyQueries is called, you may need to have an await or .then where you call it. Note that you can also use "result = await addCatalogFilters(currentCatalog)" to put the ajax result into a variable result that you can work with and pass to your $.ajax call in applyQueries. I don't know the nature of your code, so I can't make any direct suggestions.
async function applyQueries() {
// does some things
if(currentCatalog != ''){
// await on the returned Promise-like jqXHR (wait for ajax request to finish)
// recommend assigning awaited result to a variable and passing to next $.ajax
await addCatalogFilters(currentCatalog);
}
return $.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
// return the Promise-like jqXHR object: https://api.jquery.com/jQuery.ajax/#jqXHR
return $.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can use async/await. However, as no one has mentioned, I would like to demonstrate how you can accomplish this with Promise.
Lets define two functions:
function first_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/xyz',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
function second_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/abc',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
Now you can make sure that second_function() gets called only after the execution of ajax request in first_function() by following approach:
first_function(data)
.then(dataSet => {
//do other things
second_function(dataSet)
.then(dataSet2 => {
////do whatever you like with dataSet2
})
.catch(error => {
console.log(error);
});
});
I have the following code. whenever i change the value in the array - data[0] to say data[1] the value changes. i have about 4 items stored in the data array.
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://<mywebsite>/user/id/1",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("Success");
},
error: function() {
alert('Failed!');
},
}).then(function(data) {
var result = data [1];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
});
});
I want to display all the data in the array. how do i do that? I have tried doing it this way but it didnt work . i have tried other ways too , but still.
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://<mywebsite>/user/id/1",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("Success");
},
error: function() {
alert('Failed!');
},
}).then(function(data) {
var result = data [1];
console.log(result);
for (i = 0; i < result.length; i++) {
$('.ch-name').append(result[i].ch_name);
$('.ch-logo').append(result[i].ch_logo);
$('.ch-desc').append(result[i].ch_desc);
$('.ch-genre').append(result[i].ch_genre);
}
});
});
the description is a little unclear but i think i see what youre trying to do.
it should be accomplished by changing that for loop to loop over data, not results
for (i = 0; i < data.length; i++) {
$('.ch-name').append(data[i].ch_name);
$('.ch-logo').append(data[i].ch_logo);
$('.ch-desc').append(data[i].ch_desc);
$('.ch-genre').append(data[i].ch_genre);
}
if this is not what youre trying to do, please post what the structure of data looks like, and how you want to display that
I'm trying to visualize data from a JSON structure, retrieved via a REST service. I'm retrieving 3 JSON structure via a REST service, and they are dependent on each other. This means that I am nesting 3 Ajax calls. Each ajax call collects data dependent on the ajax call before. Example:
I retrieve all tasks for an department in a company. Based on data about the tasks i retrieve data about the person who requested it. Finally i retrieve data about who the task was assigned to. My code:
$( document ).ready(function() {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests?$filter=TaskStatusValue%20eq%20%27Not%20Started%27",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data){
$.each(data.d.results, function(a, data) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests("+data.RequesterId+")/CreatedBy",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data2){
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests("+data.AssignedToId+")/AssignedTo",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data3){
$(".inner").prepend('<p>'+data.Request +' <br>Submitted by: '+data2.d.Name+'<br>Assigned to: '+data3.d.Name+' | Due in: '+data.DueInDays+' day(s)</p>');
for(var i = 0; i < data3.d.Name.length; i++)
{
var AssignedTo = data3.d.Name[i];
for(var j = 0; j < AssignedTo.length; j++)
{
var version = AssignedTo[j];
}
}
console.log(version);
}
});
}
});
});
}
});
});
I'm getting all the relevant data by running an $.each loop to run through the structure. What i want to do is visualize on a graph or heatmap how many tasks have been assigned to person. So i'm trying to store the data in a javascript array, but without luck. I can see that my data is getting displayed just fine if i try to prepend it.
The problem is that by running the $.each function i get multiple instances of the same person. I would like to have (as an example) a chart which shows the persons who have assigned tasks and how many tasks.
Any suggestions on how to store and/or visualize it?
EDIT Callback structure:
function getAssignedTo(data3) {
$(".inner").prepend('<p>' + data.Request + ' <br>Submitted by: ' + data2.d.Name + '<br>Assigned to: ' + data3.d.Name + ' | Due in: ' + data.DueInDays + ' day(s)</p>');
}
function getRequester(data2) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.AssignedToId + ")/AssignedTo",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getAssignedTo(data3)
});
}
function iterateResults(a, data) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.RequesterId + ")/CreatedBy",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getRequester(data2)
});
}
function getTasks(data) {
$.each(data.d.results, function iterateResults(a, data))
}
function getHelpData() {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests?$filter=TaskStatusValue%20eq%20%27Not%20Started%27",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getTasks(data)
});
}
I have an array of symbols as shown below.
For each element of the array I am making an Ajax request.
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
$.each(symbols, function (index, value) {
loadXMLDoc(value);
});
});
function loadXMLDoc(value) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function (data) {}
}
In the browser console, I see many XHR requests under pending state.
Is it possible to make the next Ajax request only when the response has been obtained for the previous array element?
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
loadXMLDoc(symbols);
});
function loadXMLDoc(symbols) {
if(symbols[0]) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function(data){ loadXMLDoc(symbols.slice(1)) }
});
}
}
There is no value being used in loadXMLDoc in your question, I suppose you want:
url: 'https://ganaga/aaaa/'+ symbols[0],
Also, I would rename function to loadXMLDocs.
I would just use a little recursion:
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
loadXMLDoc(0);
});
function loadXMLDoc(idx) {
value = symbols[idx];
if (value) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/' + value,
success: function (data) {
//...
loadXMLDoc(idx+1);
}
});
}
}
Invoke the next AJAX call in the callback function.
function loadXMLDoc(n) {
var value = symbols[n];
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function (data) {
if (n < symbols.length-1) {
loadXMLDoc(n+1);
}
}
}
}
Start it with:
loadXMLDoc(0);
I have tried html2canvas for single div and it is working fine. Now I have 2 charts on page, so I want to capture both div in separate canvas and pass it as image. I tried following but it always set to undefined. I don't know what is the problem. When I go to debug mode in firebug I found that it doesn't go in html2canvas first, it goes in ajax and after execution of ajax, it goes to html2canvas.
$("#getPdf").click(function () {
var imageChart1, imageChart2;
html2canvas($('#loadchart1'), {
onrendered: function (canvas1) {
imageChart1 = canvas1.toDataURL("image/png");
alert(imageChart1);
imageChart1 = imageChart1.replace('data:image/png;base64,', '');
}
});
html2canvas($('#loadchart2'), {
onrendered: function (canvas2) {
imageChart2 = canvas2.toDataURL("image/png");
imageChart2 = imageChart2.replace('data:image/png;base64,', '');
}
});
if (imageChart1 != undefined && imageChart2 != undefined) {
$.ajax({
type: 'POST',
url: "/ChartReport/UploadImage",
data: ' { "image1" : "' + imageChart1 + '","image2":"' + imageChart2 + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
}
});
After edit for async:
$("#getPdf").click(function () {
var count = 0;
var imageArray = new Array("#loadchart1", "#loadchart2");
async.parallel([
function (callback) {
for (var i = 0; i < imageArray.length; i = i + 1) {
html2canvas($(imageArray[i]), {
onrendered: function (canvas) {
var imageChart1 = canvas.toDataURL("image/png").replace(' :image/png;base64,', '');
$.ajax({
type: 'POST',
url: "/ChartReport/UploadImage",
data: ' { "image1" : "' + imageChart1 + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
count = count + 1;
}
});
}
});
}
callback();
},
function (callback) {
if (count != 0) {
$.ajax({
type: 'POST',
url: "/ChartReport/makePDF",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
}
callback();
} ],
function (err, results) {
alert(results[0]);
});
});
Note: div loadchart1 is in partial view and it gets load on document.ready()
Ok, I don't know the html2canvas library, but from the looks what is going wrong is that you're confusing the flow through the code. You are assigning to imageChartN in a callback of the html2canvas function, so the if is reached before the variables can be assigned. What you should check out is async.js and use the async.parallel function.