I have been having issues getting the data I am requesting to display correctly it was being displayed as undefined.
fetch(url)
.then(res => res.json())
.then((manager) => {
/* console.log(manager); */
for (i in manager.data){
var row = $('<div id="Data">' + '<br>' + getLogo(manager, i) + '<br>'
+ '<br>' + '<p1>' + getName(manager, i) + '</p1>'
+ getAdd1(manager, i) + getAdd2(manager, i) + getAdd3(manager, i)
+ getCity(manager, i) + getPcode(manager, i)
+ '<br>' + getCountry(manager, i) + '<br>'
My issue is with the call to getCountry
+ '<br>' + getWeb(manager, i) + '<br>'
+ '<br>' + getPhases(manager, i)
+ '<br>' + getPspon(manager, i)
+ '<br>' + getOspon(manager, i) + '<br>'
+ '<br>' + getDesc(manager, i) + '<br>'
+ '<br>' + '</div>' + '<br>');
$('#Results').append(row);
}
})
};
After some research I think the problem was that the getCountry method is so long it carries on with the rest of the code and displays it as undefined.
I then came across Promises and tried to add this to the function but now the html page just shows [object Promise].
The getCountry function is shown below and was the same before the addition of the Promise code.
This is what I am trying to achieve
Checks that there is an address and then checks for a country code. Assigns the 3 digit numerical country code to country. Then loads a JSON containing ISO 3166 data process this into a searchable object. Searches the objects for a match to the value stored in country. Then assigns the name field from the matched object to result and then returns it to be displayed at the end of the address.
function getCountry(manager, i){
return new Promise(function(resolve, reject) {
if(manager.data[i].attributes.addresses[0] != null && manager.data[i].attributes.addresses[0].country != null){
var country = manager.data[i].attributes.addresses[0].country;
var c = country.toString();
let url = 'http://data.okfn.org/data/core/country-codes/r/country-codes.json';
fetch(url)
.then(res => res.json())
.then((data) => {
console.log(data);
console.log(manager);
for(var i=0, length=data.length; i<length; i++){
if(data[i].M49 === c){
var result = data[i].name;
console.log(result);
Promise.resolve(result);
}
}
})
}
else {
var reason = " ";
Promise.reject(reason);
}
}
);
}
Where am I going wrong?
Updated code using #Zohaib Ijaz suggestion
fetch(url)
.then(res => res.json())
.then((manager) => {
/* console.log(manager); */
for (i in manager.data){
/* use a Promise in order to receive the result for the below function */
getCountry(manager, i).then((cm)=> {
var row = $('<div id="Data">' + '<br>' + getLogo(manager, i) + '<br>'
+ '<br>' + '<p1>' + getName(manager, i) + '</p1>'
+ getAdd1(manager, i) + getAdd2(manager, i) + getAdd3(manager, i)
+ getCity(manager, i) + getPcode(manager, i)
+ '<br>' + cm + '<br>'
+ '<br>' + getWeb(manager, i) + '<br>'
+ '<br>' + getPhases(manager, i)
+ '<br>' + getPspon(manager, i)
+ '<br>' + getOspon(manager, i) + '<br>'
+ '<br>' + getDesc(manager, i) + '<br>'
+ '<br>' + '</div>' + '<br>');
$('#Results').append(row);
});
}
});
}
The getCountry function
function getCountry(manager, i){
return new Promise(function(resolve, reject) {
if(manager.data[i].attributes.addresses[0] != null && manager.data[i].attributes.addresses[0].country != null){
var country = manager.data[i].attributes.addresses[0].country;
var c = country.toString();
let url = 'http://data.okfn.org/data/core/country-codes/r/country-codes.json';
fetch(url)
.then(res => res.json())
.then((data) => {
for(var i=0, length=data.length; i<length; i++){
if(data[i].M49 === c){
var result = data[i].name;
/* console.log(result); */
resolve(result);
}
else {
var reason = "";
reject(reason);
}
}
})
}
else {
var reason = "";
reject(reason);
}
}
);
}
This is what I see in the Chrome console (24 times)
Uncaught (in promise) test.html:1
What I noticed is that you're calling Promise.resolve(result); when you instantiated the Promise at the start of the function, you passed it a function with two arguments, resolve and reject. Those are what you should be using to 'end' your Promise, so changing them to just resolve(result) and reject(reason) should let your Promise resolve properly.
That said, the point of a Promise is to say "do this, and when that's done, .then do this other thing". So you'd need something like
getCountry(manager, i).then(function(result) {
// result is whatever you passed into resolve() in getCountry
// everything in here is done after getCountry finishes running
// and returns a value
}, function(rejection) {
// rejection is whatever you passed into reject() in getCountry
// this only happens if things didn't work
}
I'm not sure that Promises would work since you're calling the function in the middle of a concatenation. If your other functions make asyncronous calls, an alternative you might consider is to rewrite all of your asynchronous functions as Promises, then use Promise.all() to wait for all of them to resolve before proceeding to concatenate them into HTML. Something like this
var p1 = getLogo(manager, i);
var p2 = getName(manager, i);
var p3 = getAdd1(manager, i);
...
Promise.all([p1, p2, p3]).then(function(results) {
results.join('<br>')
// Whatever else you want to happen once all the functions are finished.
})
getCountry is not a synchronous function call. You need to wait for response.
fetch(url)
.then(res => res.json())
.then((manager) => {
/* console.log(manager); */
for (i in manager.data){
getCountry(manager, i).then((cm)=> {
// Add other values as well.
var row = $('<br>' + cm + '<br>');
$('#Results').append(row);
});
}
});
Related
I am using the foreach loop to call a php page that sends back html of one gallery image.
The forEach Loop is triggered by the function galleryplayer. Gallery size can be anything from 1 to 99 photos max.
I want to use the function stopGalPlay to halt the foreach loop on the iteration it is currently on. However after a week of trying to solve this I cannot think how.
Reading about it, the consensus says that I should not be using a forEach loop. If so how would I rewrite the galleryPlayer function to use a different kind of loop and/or incorporate some mechanism to break the loop and execute the code in the stopGalPlay function.
I know the question of breaking a foreach loop has been answered a million times before but I cannot figure out how to incorporate a stop play into my image gallery.
Any help would be greatly appreciated.
Note that I want to use pure javascript without libraries like jquery or others.
var detailPageTabContentContainer = document.getElementById("detailPageTabContentContainer");
// Open the Modal
function openGalleryModal(galId, count, rowTotal) {
var galId = arguments[0];
var count = arguments[1];
var rowTotal = arguments[2];
const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + galId + "&&count=" + count + "&&rowTotal=" + rowTotal;
fetch(api_url, { method: 'get', credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
detailPageTabContentContainer.innerHTML = html;
})
.catch((err) => console.log("Can’t access " + api_url + err));
} // End of function openGalleryModal
// Close the Modal
function closeGalleryModal() {
document.getElementById("galleryModal").style.display = "none";
document.getElementById("active").click();
} // End of function closeGalleryModal
function plusGallerySlides(galId, count, rowTotal, n) {
var galId = parseInt(arguments[0]);
var count = parseInt(arguments[1]);
var rowTotal = parseInt(arguments[2]);
var n = (arguments[3]);
var GalIdFragment = (Math.floor(galId / 100));
var GalIdFragmentString = GalIdFragment.toString();
var countString;
if (count + n > rowTotal) {newCount = 1}
if (count + n < 1) {newCount = rowTotal}
if (count + n == rowTotal) {newCount = rowTotal}
if ((count + n < rowTotal)&&(count + n != 0)) {newCount = count + n}
if (count.toString().length == 1) {countString = "0" + count}
else {countString = count}
if (newCount.toString().length == 1) {countString = "0" + newCount } else {countString = newCount};
countString = countString.toString();
newGalId = GalIdFragmentString + countString;
const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + newGalId + "&&count=" + newCount + "&&rowTotal=" + rowTotal;
fetch(api_url, { method: 'get', credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
detailPageTabContentContainer.innerHTML = html;
})
.catch((err) => console.log("Can’t access " + api_url + err));
} // End of function plusGallerySlides
function stopGalPlay(galId, count, rowTotal) {
var galId = parseInt(arguments[0]);
var count = parseInt(arguments[1]);
var rowTotal = parseInt(arguments[2]);
console.log("gallery Id is " + galId + ". Count is " + count + ". Row total is " + rowTotal + ".");
const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + galId + "&&count=" + count + "&&rowTotal=" + rowTotal;
fetch(api_url, { method: 'get', credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
detailPageTabContentContainer.innerHTML = html;
})
.catch((err) => console.log("Can’t access " + api_url + err));
}
function galleryplayer(galId, count, rowTotal) {
var galId = parseInt(arguments[0]);
var count = parseInt(arguments[1]);
var rowTotal = parseInt(arguments[2]);
var GalIdFragment = (Math.floor(galId / 100));
var GalIdFragmentString = GalIdFragment.toString();
var galIdArr = [];
for ( i = 1; i <= rowTotal ; i++ ) {
galIdArr.push(i < 10 ? (GalIdFragmentString + "0" + i.toString()) : GalIdFragmentString + i.toString())
};
var interval = 4950;
var promise = Promise.resolve();
galIdArr.forEach(function (ArrayGalId, i) {
promise = promise.then(function() {
const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + ArrayGalId + "&&count=" + (i+1) + "&&rowTotal=" + rowTotal;
fetch(api_url, { method: 'get', credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
detailPageTabContentContainer.innerHTML = html;
document.getElementById("galNext").style.display = "none";
document.getElementById("galPrev").style.display = "none";
document.getElementById("galPlay").style.display = "none";
document.getElementById("galClose").style.display = "none";
document.getElementById("galPhoto").classList.add("Gallery-Player-Fade-in-Out");
})
return new Promise(function(resolve) {
setTimeout(resolve, interval);
if((i+1) === (galIdArr.length)) {
var lastGalId = (galIdArr[galIdArr.length -1]);
var galLength = galIdArr.length;
const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + lastGalId + "&&count=" + galLength + "&&rowTotal=" + rowTotal;
fetch(api_url, { method: 'get', credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
detailPageTabContentContainer.innerHTML = html;
});
};
});
});
});
}// End of function galleryplayer
You could use a while loop. while this condition is false do this. Or you could put the forEach loop inside of a function and return when it is supposed to break.
Use [].some instead of [].forEach
wherever you want to break it simply return true; it will stop the execution for further iteration.
eg
[].forEach(v => {
...
break; // does not work;
....
})
[].some(v => { // some work same as foreach if you don't return true;
....
return true; // will stop the iteration.
....
});
I have a function that connect to a web service in SOAP. Unfortunately the web service only support a very limited connections. I have an array of items to search in the web service, if i do a for or a foreach loop, the 70% of cases complete with no error, but in the 30% the web service response a error. This occurs when the max connections is overflow. This happens because the loop is no waiting the response of the webservice and the loop cotinues creating a lot of connections.
Here's my code:
var promiseArray = [];
for (var i = 0; i < result.length; i++) {
let m = result[i].id
let xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<tem:EjecutarConsultaXML>' +
'<!--Optional:-->' +
'<tem:pvstrxmlParametros>' +
'<![CDATA[' +
'<Consulta><NombreConexion>USERNAME</NombreConexion>' +
'<IdConsulta>QUERY</IdConsulta>' +
'<Parametros>' +
'<doc>' + m + '</doc>' +
'</Parametros>' +
'</Consulta>' +
']]>' +
'</tem:pvstrxmlParametros>' +
'</tem:EjecutarConsultaXML>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
const options = {
explicitArray: true
};
promiseArray.push(new Promise(async(resolve, reject) => {
await axios.post(url, xml, {
headers: {
'Content-Type': 'text/xml;charset=UTF-8'
}
})
.then((data) => {
xml2js.parseString(data.data, options, (err, result) => {
var temp = (result['soap:Envelope']['soap:Body'][0]['EjecutarConsultaXMLResponse'][0]['EjecutarConsultaXMLResult'][0]['diffgr:diffgram'][0]['NewDataSet'][0]['Resultado'])
resolve({
doc: m,
state: temp[0].f430_ind_estado[0]
})
});
})
.catch((err) => {
console.log(err)
});
}))
}
res.send(await Promise.all(promiseArray))
There are several issues with your code within the call to promiseArray.push().
There is no need to create a new Promise() since axios already provides one
This is actually and antipattern
There is no need for async/await in that call for the same reason.
Mixing Promises and functions that use callbacks usually doesn't turn out too well
You have no error checking in your code if the XML parser fails
The option object is not required as explicitArray: true is the default
Changes:
Removed all the extra/uneeded Promise code
Replaced xml2js.parseString with xml2js.parseStringPromise
Changed resolve to return
Since you're simply console.log() the error, removed unecessary boilerplate
Everything else is OK as written. Please let me know if I've missed something.
promiseArray.push(
axios.post(url, xml, {
headers: {
'Content-Type': 'text/xml;charset=UTF-8'
}
})
.then(data=>data.data)
.then(xml2js.parseStringPromise)
.then(result => {
var temp = result['soap:Envelope']['soap:Body'][0]['EjecutarConsultaXMLResponse'][0]['EjecutarConsultaXMLResult'][0]['diffgr:diffgram'][0]['NewDataSet'][0]['Resultado'];
return {
doc: m,
state: temp[0].f430_ind_estado[0]
};
});
.catch(console.log)
);
Just do it one by one, using async/await to do that, this means you have to use parseStringPromise instead.
var response = [];
for (var i = 0; i < result.length; i++) {
let m = result[i].id
let xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<tem:EjecutarConsultaXML>' +
'<!--Optional:-->' +
'<tem:pvstrxmlParametros>' +
'<![CDATA[' +
'<Consulta><NombreConexion>USERNAME</NombreConexion>' +
'<IdConsulta>QUERY</IdConsulta>' +
'<Parametros>' +
'<doc>' + m + '</doc>' +
'</Parametros>' +
'</Consulta>' +
']]>' +
'</tem:pvstrxmlParametros>' +
'</tem:EjecutarConsultaXML>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
const options = {
explicitArray: true
};
try {
var { data } = await axios.post(url, xml, { // extract data from data.data
headers: {
'Content-Type': 'text/xml;charset=UTF-8'
}
})
var xmlObject = await xml2js.parseStringPromise(data)
var temp = (xmlObject['soap:Envelope']['soap:Body'][0]['EjecutarConsultaXMLResponse'][0]['EjecutarConsultaXMLResult'][0]['diffgr:diffgram'][0]['NewDataSet'][0]['Resultado'])
response.push({
doc: m,
state: temp[0].f430_ind_estado[0]
}) // push item to result array
} catch (error) {
console.log(error);
}
}
res.send(result) // send the result to client
How to change my code, when I push the button again the information is adding to previous, I need that when I push the button the information updates.
document.querySelector(".city-select").onchange = () => {
let strUser = document.querySelector(".city-select").value;
updateInfo(strUser);
//getWeather()// при селекті
}
function updateInfo(strUser) {
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${strUser}&appid=f3ab273b1163fcf008d6d3ce02f9e86e`)
.then(function (resp) { return resp.json() })
.then(function (data) {
console.log(data);
document.querySelector('.package-name').textContent = data.name;
document.querySelector('.price').innerHTML = Math.round(data.main.temp - 273) + '°';
document.querySelector('.disclaimer').textContent = data.weather[0]['description'];
//https://openweathermap.org/img/wn/02d#2x.png
document.querySelector('.features li').innerHTML = `<img src="https://openweathermap.org/img/wn/${data.weather[0]['icon']}#2x.png">`;
document.querySelector('.button-primary').onclick = () => {
let div = document.createElement('div');
div.innerHTML = 'Wind speed: ' + data.wind.speed + ' km/h' + '<br>'+'Humidity: '+data.main.humidity + '%' + '<br>'+ 'Pressure: ' + data.main.pressure + 'Pa';
document.querySelector('.out').appendChild(div);
}
})
.catch(function () {
// catch any errors
});
}
This is because you used appendChild (https://www.w3schools.com/jsref/met_node_appendchild.asp)
Maybe you should try this instead (if there is already an element) : How to replace DOM element in place using Javascript?
I've seen many topics like this, some with pretty much the exact same title, but I'm still not finding a solution for what I'm attempting.
I basically have an HTML table that is getting data from 10 different sources. 9 of the sources I'm trying to push to an array and fund the sum, which will be one column in the table. And the other source is just a single external query result.
I'm running into problems when they take too long to load and the table has already populated.
I tried a timeout function but it doesn't seem to work even then. I'm also having issues with the table showing 10 commas separated values and not a sum, even when I add a variable =0 and then do source1+= variable for each of the sources.
Heres what I have so far, I Some of the letterers in the code are just random and a placeholder to show the structure. But this is the basic setup. I've only included 2 out of the 9 functions to save space, but its pretty much similar to the first two, 3..4..5 etc.
At a loss here, any help would be awesome and I thank you all for your valuable time.
/* HTML */
<table id="AA"> <caption>title<span id="totalValue">0</span></caption>
<tr>
<th>L</th>
<th>L Qty.</th>
<th>W</th>
<th class="value">Value</th>
<th>some text</th>
<label for="CD">
</label>
<input id="img" type="hidden" value="somedatahere" size="60" />
</tr>
</table>
//and heres the separate js
var sumqholder = 0;
$('#Form').submit(function(event) {
event.preventDefault();
$('#results').html('loading...');
var AB = $('#CD').val();
A.H.call(function(err, J) {
A.I.call(function(err, K) {
var EF = $('#EF').val();
A.G.call(EF, function(err, G) {
var results = '<b>--:</b> ';
results += G.round(5);
sumq += G;
$('#results').html(results);
});
});
$('#results2').html('loading...');
var AB = $('#CD').val();
A.H.call(function(err, J) {
A.I.call(function(err, K) {
var EF = $('#EF').val();
A.G.call(IA, function(err, G) {
var results2 = '<b>--:</b> ';
results2 += G.round(5);
sumq += G;
$('#results2').html(results2);
});
});
var sumq = sumqholder;
var L = [{
M: O,
quantity: sumq
}, {
P: " ",
quantity: x
}];
var totalValue = 0;
$(document).ready(function() {
refresh();
});
function refresh() {
$("#AA").find("tr:gt(0)").remove();
totalValue = 0;
L.forEach(function(L) {
sendRequest(L.M, L.quantity);
});
}
function sendRequest(M, L) {
var url = " " + M + "/";
$.get(url, function(data) {
addRow(data[0], quantity);
});
}
function addRow(data, quantity) {
var value = data.W * quantity;
totalValue += value;
var row = '<tr>';
row += '<td>' + data.I + '</td>';
row += '<td>' + quantity + '</td>';
row += '<td>' + data.I + '</td>';
row += '<td>' + value.toFixed(2) + '</td>';
row += '<td>' + data.O + '</td>';
row += '</tr>';
$('#AA tr:last').after(row);
updateTotalValue();
}
function updateTotalValue() {
$("#totalValue").text(totalValue.toFixed(6));
}
If i got this right, you're having problems processing data because the source is coming from 10 different async calls right? If that's the case, have each call finish off by calling a checking function.
var flag = 0;
function checkLoaded()
{
if(flag == 9){
doDataProcessing();
}else{
flag++;
}
}
This way, each call will end calling checkLoaded(); and if its the 10th one, flag will have incremented 9 times therefore we can already assume we can proceed to data processing.
This is precisely the kind of scenario that promises were designed to simplify. They will help you avoid "callback hell" and manage errors.
First, with reference to How do I Convert an Existing Callback API to Promises?, promisify all methods that accept a callback :
A.G.callAsync = function(val) {
return new Promise(function(resolve, reject) {
A.G.call(val, function(err, x) {
err ? reject(err) : resolve(x);
});
});
};
A.H.callAsync = function() {
return new Promise(function(resolve, reject) {
A.H.call(function(err, x) {
err ? reject(err) : resolve(x);
});
});
};
A.I.callAsync = function() {
return new Promise(function(resolve, reject) {
A.I.call(function(err, x) {
err ? reject(err) : resolve(x);
});
});
};
jQuery's $.get() already returns a promise therefore doesn't need to be promisified.
Then, everything else can be done inside a $(document).ready(function() {...}) structure, something like this :
$(document).ready(function() {
$('#Form').submit(function (event) {
event.preventDefault();
$('#results').html('loading...');
// promise chain for the first A.H(), A.I(), A,G() sequence.
var promise1 = A.H.callAsync().then(function(J) {
return A.I.callAsync();
}).then(function(K) {
return A.G.callAsync($('#AB').val());
}).then(function(G) {
$('#results').html('<b>--:</b> ' + G.round(5));
return G; // the chain delivers this value
});
// promise chain for the second A.H(), A.I(), A,G() sequence.
var promise2 = promise1.then(function() {
$('#results2').html('loading...');
return A.H.callAsync().then(function(J) {
return A.I.callAsync();
}).then(function(K) {
return A.G.callAsync($('#EF').val());
}).then(function(G) {
$('#results2').html('<b>--:</b> ' + G.round(5));
return G; // the chain delivers this value
});
});
Promise.all([promise1, promise2]) // aggregate promise1 and promise2
.then(function(G_values) { // G_values is an array containing the `G` values delivered by promise1 and promise2.
var sumq = G_values.reduce(function(runningTotal, val) {
return runningTotal + val;
}, 0);
var L = [
{ 'M': O, 'quantity': sumq }, // what is O?
{ 'P': ' ', 'quantity': x } // where's 'M'? what is 'x'
// ...
];
$("#AA").find("tr:gt(0)").remove();
return Promise.all(L.map(sendRequest)) // aggregate all the promises returned by sendRequest()
.then(function(values) { // `values` is an array of values delivered by the promises returned from sendRequest().
var totalValue = values.reduce(function(runningTotal, val) {
return runningTotal + val;
}, 0); // ie values[0] + values[1] + ...
$("#totalValue").text(totalValue.toFixed(6));
});
function sendRequest(item) {
var url = ' ' + item.M + '/';
var $tr = $('<tr/>').insertAfter('#AA tr:last'); // inserting here ensures the <tr>s are in the same order as the objects in `L`.
return $.get(url)
.then(function(data) {
return addRow(data[0], item.quantity, $tr); // deliver addRow's return value to Promise.all() above
});
}
function addRow(data, quantity, $tr) {
var value = data.W * quantity;
var cells = '<td>' + data.I + '</td>'
+ '<td>' + quantity + '</td>'
+ '<td>' + data.I + '</td>'
+ '<td>' + value.toFixed(2) + '</td>'
+ '<td>' + data.O + '</td>';
$tr.html(cells);
return value; // for on-screen consistency, you may choose to `return Number(value.toFixed(2))`
}
}).catch(function(err) {
console.error(err);
});
});
});
I'm not sure that's 100% what you want but it should give you a good idea how to solve an asynchronous javascript problem.
I have two Jquery function. How do I set the execution order so that function B would only be called after function A, (reason behind is that Function A set a value to a variable IdstoExclude that is getting passed as a parameter to function B.
Below is what i tried but no luck:
var IDstoExclude = "123";
callListService('getArticleTypelistById', 'Atid', 87, 5, '#MainStory', '#tmplFeaturePanel', IDstoExclude);
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude);
function callListService(webServiceName, parameterName, parameterValue, noOfItems, domElement, templName, exclIDs) {
//set a default value for the template name * exclIDs
templName = templName || "#FeaturedSubStories";
//exclIDs = exclIDs || "123,12";
var inputParameters = webServiceName.toLowerCase() + ':' + parameterName.toLowerCase() + ':' + parameterValue + ':noofitems:' + noOfItems + ':excludeids:' + exclIDs;
var clientcode = getCryptoToken(inputParameters);
//Build JSONp query
eval("data={" + parameterName.toLowerCase() + ":" + parameterValue + ", noofitems: " + noOfItems + ", excludeids:" + exclIDs + ", clientcode:'" + clientcode + "' }");
$.getJSON('https://abc.com/Service.svc/' + webServiceName + '?callback=?', data, function (data2) {
var template = $.templates(templName);
var htmlOutput = template.render(data2);
$(domElement).append(htmlOutput);
IDstoExclude = data2.IdsInThisList;
});
Tried below but no luck: var IDstoExclude = "123";
function callService1() {
return $.ajax()
.then(function(response) {
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude);
});
}
function callService2() {
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude)
}
$.when(callService1()).then(callService2);
For this solution to work as you expect your code should look like something below:
function callService1(p1, p2, ...) {
return $.ajax(...)
.then(function(response) {
return something;
});
}
function callService2(something_from_s1) {
// work with something_from_s1 var
}
$.when(callService1(...)).then(callService2);
References:
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://api.jquery.com/category/deferred-object/
http://api.jquery.com/deferred.then/