Dynamic API CALL/ Retrieving specific Attributes - javascript

I am doing an API call and data fetching with Fetch function on a platform listing different products with their data identified by attributes, here I am trying to fetch multiple attributes of a specific category of product, each product is identified by a unique serial number, which serves as my entry key to retrieve product data.
Or the attributes that I retrieve do not exist for certain products, either the field exists but the data is null, or the field is not filled in on the platform for this product.
I neutralize nulls with the formula you can see on my script but it doesn't always work, I would like to know if I can make my API even more dynamic, i.e. retrieve attributes only when they exist and when the presence of a null does not block the API call.
function GetAllProduct() {
var token=ConnectAlkemics();
//Logger.log(token);
var headers ={
"accept": "*/*",
"accept-language": "fr",
'Authorization' : 'Bearer ' + token,
'cache-control': 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'expires': '-1',
'pragma': 'no-cache',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'x-alk-priority': '9'
};
var options ={
'method' : "GET",
"headers" : headers
};
var source =SpreadsheetApp.getActive().getSheetByName("GTIN");
var ss =SpreadsheetApp.getActive().getSheetByName("RESULTATS");
ss.clear();
// var dico=CreerDicoHeader();
//retrieving list of attribute
var lastRow = source.getLastRow();
var listeAttribut = "";
var listeChamp = "";
var tabChamp = [];
var index = 0;
for(var i = 2; i <= lastRow; i++ ){
//Logger.log(i);
if(source.getRange(i, 3).getValue() != ""){
tabChamp[index] = source.getRange(i, 2).getValue();
index +=1;
if(listeAttribut == ""){
listeAttribut = source.getRange(i, 3).getValue();
listeChamp = source.getRange(i, 2).getValue();
}
else{
listeAttribut = listeAttribut + "," + source.getRange(i, 3).getValue();
listeChamp = listeChamp + "," + source.getRange(i, 2).getValue();}
}
}
var total=0;
var debut=2;
var moregtin=true
var lignegtin=1;
var colonnes=[
"GTIN",
"Libelle long",
"Fournisseur",
"Catégorie du produit",
"Code Tiers",
"Cycle de vie",
"Maturité commande Galec",
"Maturité direct magasin" ,
"Maturité Commande SCABEL",
"Maturité complémentaire Galec",
"Maturité complémentaire Direct Magasin",
"Maturité complémentaire Scabel",
"Maturité Animation Digitale",
"Maturité Digitale",
"Maturité Entité Leclerc",
"Type d'unité",
"Marque Commerciale",
"Appellation viticole ou région d'origine",
"Complément d'appellation(N)",
"Packaging vin",
"Contenu net",
"Description des saveurs du vin",
"Type de champagne(N)",
"Viticulture(N)",
"Couleur du Vin",
"Millésime",
"Terroirs et sol(N)",
"Région Viticole",
"Durée du potentiel de maturation",
"Echelle de fruit",
"Echelle de personnalité",
"Dégustation robe",
"Dégustation nez",
"Type de vendange(N)",
"Dégustation bouche",
"Type d'appellation du vin",
"Allergènes avérés",
"Type d'allergène",
"Degré d'alcool",
"Teneur en sucre",
"Description du cépage",
"Accords mets et vins",
"Occasions particulières",
"Températures de dégustation (en °c)",
"Potentiel de garde",
"Code de nomenclature douanière",
"Code produit accise france",
"Libellé fiscal",
"Pays d'origine",
"Type de paiement des droits d'alcools",
"Image Face du produit",
"Image Arrière du produit",
];
var colonnematurite=6; //Colonnes
for(i=0;i<colonnes.length;i++) {
ss.getRange(1,i+1).setValue(colonnes[i]);
}
//for(i=0; i<tabChamp.length; i++){
// ss.getRange(1,i+1).setValue(tabChamp[i]);
//Logger.log(tabChamp[i]);
//}
while (moregtin==true)
{
var fini=false;
var nbgtin=0;
var lesgtin="";
var produits =[];
while ((source.getRange(lignegtin,1).getValue()!="") && (nbgtin<50)) //paquets de 50 GTINs
{
if (lesgtin!="")
lesgtin=lesgtin+",";
lesgtin=lesgtin+source.getRange(lignegtin,1).getValue().toString().replace(/\s+/g," ").trim();
lignegtin=lignegtin+1;
nbgtin=nbgtin+1;
}
if (lesgtin=="")
{
moregtin=false;
fini=true;
}
else
{
var limit=200;
var next_page='';
var lastparam='';
var params =lastparam + 'status_shared_from=4' + lesgtin + '&filter_source_include=uuid,gtin,namePublicLong,namePublicShort,isSharedFrom.sourceOrganization.nameLegal,endAvailabilityDateTime,supplierId,business_processes,brand.description,lastOrderDateTime,isUserLabeledByName,lifeCycle,typePackaging,isConsumerUnit,isBaseUnit,isDisplayUnit,assets,pictures,exportables'
var params =lastparam + '&filter_product_languages=fr&filter_gtins_in=' + lesgtin + '&filter_source_include=' + listeAttribut
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
}
while (fini==false) {
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
var url='https://apis.alkemics.com/public/v1/products?'+lesparams;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content.getResponseCode() ==200) {
var retour =JSON.parse(content.getContentText());
next_page=retour.next_page;
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var libellelong="";
try
{
libellelong=produit.namePublicLong[0].data;
}
catch(e) {
libellelong="";
//libelle="NA"
}
var libellecourt="";
try
{
libellecourt=produit.namePublicShort[0].data;
}
catch(e) {
libellecourt="";
//libelle="NA"
}
var maturite={}
for(k=0;k<produit.business_processes.length;k++)
{
maturite[produit.business_processes[k].label]=(produit.business_processes[k].requested==false?"":(produit.business_processes[k].status==true?"OK":"KO"));
}
var listematurite={}
for(k=0;k<produit.business_processes.length;k++)
{
listematurite[k]=produit.business_processes[k].label;
}
var marque=""
if ("brand" in produit) {
if ("description" in produit.brand)
marque=produit.brand.description;
}
var occasionwhine=""
if (" occasions" in produit) {
if("occasion" in produit.occasions[0])
occasionwhine = produit.occasions[0].occasion.label
}
var pairing=""
if (" pairingsTypes" in produit) {
if("pairingsType" in produit.pairingsTypes[0])
pairing = produit.pairingsTypes[0].pairingsType.label
}
var mediaface= ""
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[0])
mediaface= produit.assets.pictures[0].exportables[0].uniformResourceIdentifier
}
var mediaback
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[2])
mediaback= produit.assets.pictures[2].exportables[0].uniformResourceIdentifier
}
//var ConsumerUnit = (produit.isConsumerUnit == false ?"":(produit.isBaseUnit==true?"UC":"LOT"))
//var Presentoir = (produit.isDisplayUnit == true ? produit.typePackaging.label : "")
var ligne=[
produit.gtin,
libellelong,
produit.isSharedFrom[0].sourceOrganization.nameLegal,
produit.kind != null? produit.kind.label: ' ',
produit.supplierId,
produit.lifeCycle,
//(produit.endAvailabilityDateTime==null?"":TIMESTAMP_TO_DATE(produit.endAvailabilityDateTime)),
//produit.isUserLabeledByName,
maturite[tabChamp[colonnematurite]],
maturite[tabChamp[colonnematurite+1]],
maturite[tabChamp[colonnematurite+2]],
maturite[tabChamp[colonnematurite+3]],
maturite[tabChamp[colonnematurite+4]],
maturite[tabChamp[colonnematurite+5]],
maturite[tabChamp[colonnematurite+6]],
maturite[tabChamp[colonnematurite+7]],
maturite[tabChamp[colonnematurite+8]],
produit.typePackaging.label,
marque,
produit['alcoholicBeverageSubregionText'],
produit['alcoholicBeverageAdditionalAppellationDetailsText'],
produit.leclercWinePackagingTypeCode != null? produit.leclercWinePackagingTypeCode.label : ' ',
produit.netWeight[0] != null? produit.netWeight[0].data: ' ',
produit.wineTastingDescriptionList[0] != null?
produit.wineTastingDescriptionList[0].wineTastingCode.label : ' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.vintnerTextList,
produit.colorGroup != null? produit.colorGroup.label: ' ',
produit.vintage,
produit.vineyardRegion != null? produit.vineyardRegion.label: ' ',
produit.leclercFrenchVineyardRegionCode != null? produit.leclercFrenchVineyardRegionCode.label: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label: ' ',
produit.wineFruitExpressionNoteNumber,
produit.wineAromasExpressionNoteNumber,
produit.wineTastingRobeDescriptionText[0] != null? produit.wineTastingRobeDescriptionText[0].data: ' ',
produit.wineTastingNoseDescriptionText[0] != null? produit.wineTastingNoseDescriptionText[0].data: ' ',
produit['grapeHarvestingDescriptionText'].data,
produit.wineTastingMouthDescriptionText[0] != null? produit.wineTastingMouthDescriptionText[0].data:' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.allergens[0] != null? produit.allergens[0].data : ' ',
produit.allergenTypeList,
produit.ratioAlcohol,
produit.sugarContent != null? produit.sugarContent.label: ' ',
produit.varietalDesignationDescriptionText[0] != null? produit.varietalDesignationDescriptionText[0].data:' ',
pairing,
//produit.pairingsTypes[0] != null? produit.pairingsTypes[0].pairingsType.label: ' ',
occasionwhine,
//produit.occasions[0].occasion != null? produit.occasions[0].occasion.label: ' ' , //+ "," + produit.occasions[1],
produit.tempConsumption[0] != null? produit.tempConsumption[0].data: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label : ' ',
produit.importEuropeanClassification,
produit.cpaFranceCode.label,
produit.taxLabelList[0] != null? produit.taxLabelList[0].taxLabelCode.label: ' ',
produit.countryOfOriginList[0] != null? produit.countryOfOriginList[0].countryOfOriginCode.label: ' ',
produit.alcoholicBeveragePaymentTypeCode != null? produit.alcoholicBeveragePaymentTypeCode.label: ' ',
mediaface,
mediaback,
//produit.assets.pictures[0].exportables[0] != null? produit.assets.pictures[0].exportables[0].uniformResourceIdentifier: ' ',
// produit.assets.pictures[2].exportables[0] != null? produit.assets.pictures[2].exportables[0].uniformResourceIdentifier: ' ',
//ConsumerUnit,
//Presentoir
];
produits.push(ligne);
total=total+1;
}
}
else {
Logger.log('Error in GET /contents/{contentid}')
}

Related

async functions inside jquery each() loops

I have a loop running for each selected checkbox in Javascript / Jquery.
Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.
$('#exec-perm').on('click', function () {
var checkboxPermanent;
$('#checks-perm input').each(async function () {
checkboxPermanent = $(this).attr('value');
isChecked = $(this).prop('checked');
permanent = permanent_layers[checkboxPermanent] // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
pixel_permanent = pixel_permanent_layers[checkboxPermanent]
if (permanent) {
if (!isChecked) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
} else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
//map.addLayer(permanent)
//map.addLayer(pixel_permanent)
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
} else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
} else if (isChecked) {
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
//console.log(checkboxPermanent)
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
if (checkboxPermanent == 'altimetria') {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
} else {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
}
});
})
If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..
async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
//var colorRampSLD = getStyles(faz_value, checkboxPermanent)
if (checkboxPermanent == 'altimetria') {
var raster_name = checkboxPermanent + '_' + faz_value
getColors = await getStyles(faz_value, checkboxPermanent)
var colorEnv = '';
for (var j = 0; j < getColors.length; j++) {
if (j + 1 >= getColors.length) {
colorEnv += 'c' + j + ':' + getColors[j]
} else {
colorEnv += 'c' + j + ':' + getColors[j] + ';'
}
}
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + raster_name,
transparent: true,
format: 'image/png',
}).setParams({
env: colorEnv
})
} else {
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
transparent: true,
format: 'image/png',
})
}
}
What Am I missing here?
Check here:
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.
You need to wait for the result of wmsPermRasterCall using await:
console.log(checkboxPermanent)
permanent = await wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
Your code will halt until wmsPermRasterCall is finished.

Order in jQuery calls

I have a jQuery loop that iterates over specifics elements of an HTML page. For every element, I do a switch over a variable and append HTML code in specific places.
The problem is that, one of those appends is an import to another Javascript file. This file uses a variable from the first one but, for some reason, that variable doesn't always have the correct value, depending on the order of the HTML elements in the page.
UPDATE
As requested, I created a Plunker so it's easy to see code:
http://plnkr.co/edit/mrEhgbZhhvu0Z4iniXGl?p=preview
Note: For this to work, you need to have correct pageId and appId for Instagram.
I'll put the code to be more clear:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<section id="rrss">
<!-- If I put this article block as the last one, it works -->
<article id="instagram">
<div data-rrss="instagram"></div>
</article>
<br/>
<article id="facebook">
<div data-rrss="facebook"></div>
</article>
<br/>
<article id="twitter">
<div data-rrss="twitter"></div>
</article>
</section>
<!-- SCRIPTS -->
<script src='scripts/data.js'></script>
<script src='scripts/jquery.js'></script>
<script>var customJquery = $.noConflict(true);</script>
<script src='../magic.js'></script>
</body>
</html>
data.js
var data = {
"facebook": {
"id": "facebook",
"width": 0,
"height": 0,
"custom_style": "border:none;overflow:hidden",
"hide_cover": false,
"show_facepile": true,
"small_header": false,
"adapt_container_width": true
},
"twitter": {
"id": "twitter",
"width": 0,
"height": 0,
"chrome": "nofooter noscrollbar noheader", // noborders transparent
"tweet_limit": 0,
"lang": "es",
"theme": "dark",
"link_color": "#0084b4"
},
"instagram": {
"id": "123456798123467/9876543219876543",
"hidecaption": false,
"custom_style": "overflow:auto;",
"max_width": 0,
"max_height": 500
},
"defaults": {
"width": 380,
"height": 500
}
}
magic.js
var rrss = customJquery('div[data-rrss]');
var conf = undefined;
var defaults = undefined;
var node = document.querySelectorAll('[data-rrss="instagram"]')[0];
customJquery.each(rrss, function(ix, it) {
var html = '';
var network = customJquery(it).data('rrss');
if (network === undefined || network == null || network.length <= 0)
return;
conf = data[network];
if (conf === undefined ||conf === null || conf.length <= 0)
return;
defaults = data['defaults'];
//Comprobamos si existe el key y si el value tiene texto
if(conf.id === undefined || conf.id === null || conf.id.length === 0)
return;
switch(network) {
case 'facebook':
html = '<iframe id="iFB" src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2F' + conf.id +
'&tabs=timeline' +
'&width=' + (conf.width <= 0 ? defaults.width : conf.width) +
'&height=' + (conf.height <= 0 ? defaults.height : conf.height) +
'&small_header=' + conf.small_header +
'&adapt_container_width=' + conf.adapt_container_width +
'&hide_cover=' + conf.hide_cover +
'&show_facepile=' + conf.show_facepile + '"' +
'width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ' +
'style="' + conf.custom_style + '" ' +
'scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>\n' +
'<script type="text/javascript">\n' +
' setInterval(() => {\n' +
' customJquery("#iFB")[0].src = customJquery("#iFB")[0].src\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
case 'twitter':
html = '<a class="twitter-timeline" '+
'href="https://twitter.com/' + conf.id + '" ' +
'data-width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'data-height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ';
if (conf.chrome !== undefined && conf.chrome !== '') {
html += 'data-chrome="' + conf.chrome + '" ';
}
if (conf.tweet_limit > 0) {
html += 'data-tweet-limit="' + conf.tweet_limit + '" ';
}
html += 'data-lang="' + conf.lang + '" ' +
'data-theme="' + conf.theme + '" ' +
'data-link-color="' + conf.link_color + '"' +
'>Tweets by ' + conf.id + '</a>\n' +
'<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>';
break;
case 'instagram':
node = node.parentElement;
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../insta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
default:
html = '';
}
if (html != '') {
customJquery(it).replaceWith(html);
}
});
insta.js
window.fbAsyncInit = function () {
var html = '';
var style = '';
// When the Instagram's article bloke in HTML isn't the last one, this shows data from Twitter bloke
console.log(conf);
if (node !== undefined) {
if (document.getElementById('instagram') !== null) {
document.getElementById('instagram').innerHTML = '';
}
if (conf !== undefined && conf !== '') {
if (conf.max_width !== undefined && conf.max_width > 0) {
style += 'max-width: ' + conf.max_width + 'px;';
} else {
style += 'max-width: ' + defaults.width + 'px;';
}
if (conf.max_height !== undefined && conf.max_height > 0) {
style += 'max-height: ' + conf.max_height + 'px;';
} else {
style += 'max-height: ' + defaults.height + 'px;';
}
style += conf.custom_style;
}
var div = document.createElement('div');
div.id = 'instagram';
if (style !== '') {
div.style = style;
}
node.appendChild(div);
}
var pageId = conf.id.substring(0, conf.id.indexOf('/'));
var appId = conf.id.substring(conf.id.indexOf('/') + 1);
FB.init({
appId: appId,
autoLogAppEvents: true,
xfbml: true,
version: "v3.1"
});
FB.getLoginStatus(function (response) {
if (response.status === "connected") {
FB.api(
"/" + pageId + "/",
"GET", { "fields": "instagram_business_account" },
function (response) {
if (response.error && response.error !== '') {
console.log("Error recovering 'instagram_business_account': " + response.error.message);
} else {
FB.api(
"/" + response.instagram_business_account.id + "/media",
"GET", { "fields": "shortcode" },
function (response) {
for (var i = 0; i < response.data.length; i++) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
html = JSON.parse(this.response).html;
document.getElementById("instagram").innerHTML += html;
}
};
xhttp.open("GET", "https://api.instagram.com/oembed/?url=http://instagr.am/p/" + response.data[i].shortcode + "&omitscript=true&hidecaption=" + conf.hidecaption, true);
xhttp.send();
}
}
);
}
}
);
} else {
console.log("Error recovering access token: Not connected.")
console.log(response)
}
});
};
Well, I've solved with some ugly lonely line:
case 'instagram':
node = node.parentElement;
instaconf = conf; // ***** Saved the conf here *****
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../tecInsta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
Then changed the conf references to instaconf in insta.js file.
Since this file was loaded after the jQuery loops ended, the configuration was the last one in that loop (the last article in index.html file).
Here the problem is you are appending HTML elements dynamically. Here jquery will append in DOM then browser will some time to parse. Until that controller wont wait for the operation so loop continue execution. so here config is hold last element of twitter configuration.
And we can't pass reference to html string as per my knowledge. This we can achieve by passing config as string into html string from there we can pass to fbAsyncInit() method.
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' let configuration = '+ JSON.stringify(conf) +';'+
' fbAsyncInit(configuration);\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
and we can receive as
window.fbAsyncInit = function (con) {
or we can pass call back function to html method and we do operation which is done in magic.js
Reference: http://api.jquery.com/html/#html-function
then we can return html accordingly.
I hope this will help you.

How to put id IS NOT NULL with escape varible ??/?

I tried to put 3 variations are included:
empty
version IS NOT NULL AND
version = ' + criteria.version + ' AND
I need use escape
Help please
this code is wrong, but for understanding I need like this:
function getCriteria(criteria){
var ver = '';
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ' + criteria.version + ' AND';
}
return mysql.getConnection((conn) => {
return conn.queryAsync('SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ? create_timestamp < "2017-02-16 13:34:40"', [ver]).then............
You could build the query text using regular string handling, but still use the parameterization for the case where you need it;
function getCriteria(criteria) {
var ver = '';
var parms = []
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ? AND';
parms = [criteria.version]
}
return mysql.getConnection((conn) => {
return conn.queryAsync(
'SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ' + ver + ' create_timestamp < "2017-02-16 13:34:40"', parms)
.then............

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});

compare special characters with variable javascript

I have a code that compares if a variable that I get is equal to a certain value. So the code is something like this:
if (data[name] == '1222 €'){
ResultField = ResultField + 'Beschrijving van de maningsprocedure: : rekeningoverzichten ' + '<br>';
}
The problem is that what I get is for example '1222 €'. '1222 €' == '1222 €' is false so it won't enter inside the if. And If I put the code like this:
if (data[name] == '1222 €'){
ResultField = ResultField + 'Beschrijving van de maningsprocedure: : rekeningoverzichten ' + '<br>';
}
The code don't even start to execute due to the special character. So how can I do to make '1222 €' == '1222 €' true?
This is all the code that I am using:
$(function() {
setTimeout(function() {
DINK.utils.input.formula.add({
path : 'IbanDrive/Newcollection/eurosymbol',
types : {
'IbanDrive/Newcollection/eurosymbol/FrequentieVanDeManingsprocedure' : 'text',
'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen' : 'text',
'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen2' : 'text',
'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen3' : 'text',
'IbanDrive/Newcollection/eurosymbol/HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden' : 'array',
'IbanDrive/Newcollection/eurosymbol/empty' : 'text',
'IbanDrive/Newcollection/eurosymbol/empty2' : 'text',
'IbanDrive/Newcollection/eurosymbol/empty3' : 'text',
'IbanDrive/Newcollection/eurosymbol/debiteuren' : 'text',
'IbanDrive/Newcollection/eurosymbol/debiteuren2' : 'text',
'IbanDrive/Newcollection/eurosymbol/debiteuren3' : 'text',
'IbanDrive/Newcollection/eurosymbol/BeschrijvingVanDeManingsprocedure' : 'text',
'IbanDrive/Newcollection/eurosymbol/ZoJaVoorWelkBedragAantalDebiteuren' : 'array',
'IbanDrive/Newcollection/eurosymbol/testDim' : 'text'
},
names : {
'IbanDrive/Newcollection/eurosymbol/testDim' : 'testDim'
},
change : {
},
anyChange : function(data) {
var FrequentieVanDeManingsprocedure = 'IbanDrive/Newcollection/eurosymbol/FrequentieVanDeManingsprocedure';
var tijdstipVdagen = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen';
var tijdstipVdagen2 = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen2';
var tijdstipVdagen3 = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen3';
var HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden = 'IbanDrive/Newcollection/eurosymbol/HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden';
var empty = 'IbanDrive/Newcollection/eurosymbol/empty';
var empty2 = 'IbanDrive/Newcollection/eurosymbol/empty2';
var empty3 = 'IbanDrive/Newcollection/eurosymbol/empty3';
var debiteuren = 'IbanDrive/Newcollection/eurosymbol/debiteuren';
var debiteuren2 = 'IbanDrive/Newcollection/eurosymbol/debiteuren2';
var debiteuren3 = 'IbanDrive/Newcollection/eurosymbol/debiteuren3';
var BeschrijvingVanDeManingsprocedure = 'IbanDrive/Newcollection/eurosymbol/BeschrijvingVanDeManingsprocedure';
var ZoJaVoorWelkBedragAantalDebiteuren = 'IbanDrive/Newcollection/eurosymbol/ZoJaVoorWelkBedragAantalDebiteuren';
var testDim = 'IbanDrive/Newcollection/eurosymbol/testDim';
console.log('write this');
var dinkResultField = '';
if (data[FrequentieVanDeManingsprocedure] == 'wekelijks'){
dinkResultField = dinkResultField + 'Frequentie van de maningsprocedure:: wekelijks' + '<br>';
}
if (data[FrequentieVanDeManingsprocedure] == '14 daags'){
dinkResultField = dinkResultField + 'Frequentie van de maningsprocedure:: 14 daags' + '<br>';
}
if (data[FrequentieVanDeManingsprocedure] == 'maandelijks'){
dinkResultField = dinkResultField + 'Frequentie van de maningsprocedure:: maandelijks' + '<br>';
}
if (data[HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden] != undefined){
if (data[HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden].length != 0){
dinkResultField = dinkResultField + 'Heeft u de laatste drie jaar debiteurenverliezen geleden ? : ';
for (i = 0; i < data[HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden].length; i++) {
if (data[HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden][i] == 'ja '){
dinkResultField = dinkResultField + 'ja ';
}
if (data[HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden][i] == 'nee'){
dinkResultField = dinkResultField + 'nee ';
}
}
dinkResultField = dinkResultField + '<br>';
}
}
if (data[ZoJaVoorWelkBedragAantalDebiteuren] != undefined){
if (data[ZoJaVoorWelkBedragAantalDebiteuren].length != 0){
dinkResultField = dinkResultField + 'Zo ja, voor welk bedrag + aantal debiteuren : ';
for (i = 0; i < data[ZoJaVoorWelkBedragAantalDebiteuren].length; i++) {
if (data[ZoJaVoorWelkBedragAantalDebiteuren][i] == 'jaar &#8211 1€'){
dinkResultField = dinkResultField + 'jaar &#8211 1 ';
}
if (data[ZoJaVoorWelkBedragAantalDebiteuren][i] == 'jaar &#8211 2'){
dinkResultField = dinkResultField + 'jaar &#8211 2 ';
}
if (data[ZoJaVoorWelkBedragAantalDebiteuren][i] == 'jaar &#8211 3'){
dinkResultField = dinkResultField + 'jaar &#8211 3 ';
}
}
dinkResultField = dinkResultField + '<br>';
}
}
if (data[BeschrijvingVanDeManingsprocedure] == 'rekeningoverzichten '){
dinkResultField = dinkResultField + 'Beschrijving van de maningsprocedure: : rekeningoverzichten ' + '<br>';
}
if (data[BeschrijvingVanDeManingsprocedure] == 'telefonische maningen '){
dinkResultField = dinkResultField + 'Beschrijving van de maningsprocedure: : telefonische maningen ' + '<br>';
}
if (data[BeschrijvingVanDeManingsprocedure] == 'ingebrekestelling '){
dinkResultField = dinkResultField + 'Beschrijving van de maningsprocedure: : ingebrekestelling ' + '<br>';
}
data[testDim] = dinkResultField;
},
beforeSubmit : function(event, data, params) {
var FrequentieVanDeManingsprocedure = 'IbanDrive/Newcollection/eurosymbol/FrequentieVanDeManingsprocedure';
var tijdstipVdagen = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen';
var tijdstipVdagen2 = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen2';
var tijdstipVdagen3 = 'IbanDrive/Newcollection/eurosymbol/tijdstipVdagen3';
var HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden = 'IbanDrive/Newcollection/eurosymbol/HeeftUDeLaatsteDrieJaarDebiteurenverliezenGeleden';
var empty = 'IbanDrive/Newcollection/eurosymbol/empty';
var empty2 = 'IbanDrive/Newcollection/eurosymbol/empty2';
var empty3 = 'IbanDrive/Newcollection/eurosymbol/empty3';
var debiteuren = 'IbanDrive/Newcollection/eurosymbol/debiteuren';
var debiteuren2 = 'IbanDrive/Newcollection/eurosymbol/debiteuren2';
var debiteuren3 = 'IbanDrive/Newcollection/eurosymbol/debiteuren3';
var BeschrijvingVanDeManingsprocedure = 'IbanDrive/Newcollection/eurosymbol/BeschrijvingVanDeManingsprocedure';
var ZoJaVoorWelkBedragAantalDebiteuren = 'IbanDrive/Newcollection/eurosymbol/ZoJaVoorWelkBedragAantalDebiteuren';
var testDim = 'IbanDrive/Newcollection/eurosymbol/testDim';
}
});
}, 1300);
});
You need to use the DOM to make your browser render the HTML and then extract the resulting plain text. To do so you can use the techniques explained at Strip HTML from Text JavaScript. Basically, you inject your HTML string into a fake node and call textContent or innerText (older Internet Explorer) from the element's HTML.
Still, beware of differences in white space, accents, case and the like.
I can't speak your language (Dutch?) but you're clearly generating HTML yourself:
dinkResultField = dinkResultField + 'Frequentie van de maningsprocedure:: wekelijks' + '<br>';
Your code basically builds a long HTML string. Most likely, you're trying to parse it at a later stage. Just store data in a convenient format. Instead of:
var amount = "Total: 1234 €";
... do this:
var display = "Total: 1234 €";
var amount = 1234;
Notations like € are HTML escapes for characters and should not be expected to work in JavaScript. Use the characters themselves, as in data[name] == '1222 €' and make sure that you have declared character encoding of the JavaScript file properly. A simple way to achieve this is to write the file with an editor that lets you save it in UTF-8 format with BOM (since BOM, Byte Order Mark, acts as an indication of character encoding).
Should this be impossible for some odd reason, use a JavaScript escape, e.g. as in
data[name] == '1222 \u20AC'

Categories