compare special characters with variable javascript - 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'

Related

Javascript chinese variable being passed to bash script as question mark

I have this javascript function here, the routeno variable will pass a Chinese value
routeno: 粤ZX123港
function getRouteLegNoList()
{
var data = "host="+lphost
+ "&user="+user
+ "&gateway="+gateway
+ "&routedate="+routedate.value
+ "&routeno="+routeno.value
+ "&action=GETROUTELEGNOLIST";
alert(lphost+'|'+user+'|'+gateway+'|'+routedate.value+'|'+routeno.value);
callAjax("../restartAndMoveDeclaration.cgi?"+data, "GET", "",
function(text) {
alert(text);
var html = "<select id=routelegno>";
var count = 0;
var lines = text.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var line = lines[i];
var c;
if(line.indexOf("Data|") == 0) {
count += 1;
c = line.split("|");
html += "<option value=\"" + c[1]
+ "\"";
if(c[1]==origRouteLegNo) {
html += " selected ";
}
html += ">" + c[1] + "</option>";
}
}
html += "</select>";
dvroutelegno.innerHTML = html;
if(count==0){
alert('No Route Legs were found for [' +
gateway + '] [' +
routedate.value + '] [' +
routeno.value + ']');
} else {
if(count==1) {
trroutelegno.style.visibility = 'hidden';
} else {
// More than one, display the select box
trroutelegno.style.visibility = 'visible';
}
}
}
);
}
but when shell script captured the variable it does not read the Chinese character and replaced it as question mark
routeno: ?ZX123?
I've already tried to set different NLS_LANG but encountered the same output
NLS_LANG=AMERICAN_AMERICA.ZHS16GBK
NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Dynamic API CALL/ Retrieving specific Attributes

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}')
}

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.

Javascript : How access to a local function from global code

I have a function inside of an immediately invoked function expression and I want to be able to access that function globally without lexically scoping it that way.
How can I access this "private" function through a namespace called "App"?
indew.html:
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="filtering.js"></script>
</head>
<body>
<article>
<p>
Computer graphics is widespread today. Computer imagery is found on televi
surfaces, illumination sources, and so forth, perhaps with a dynamic (time) component".[3]
</p>
</article>
<section id="result"></section>
<script>
App.showOccurenceFiltering(); // here is my wrong call
</script>
</body>
</html>
js script :
var App = (function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
}(App));
so i got an error of a miss call like shows the capture :
how should i resolve my problem ??
You'll need to expose the function to the global scope. You can do this with a namespace, like this:
(function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
// Prepare a "dummy" object
var obj = {};
// Attach the private function to this object
obj.showOccurenceFiltering = showOccurenceFiltering;
// Attach the dummy object to the global scope in a controlled namespace:
window.App = obj;
}());
Then you can access the function like this:
App.showOccurenceFiltering();
You could do the following:
var App = (function(){
var obj = {};
obj.showOccurenceFiltering = function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
return obj;
}());
Your App variable remains undefined because the Immediately Invoked Function Expression does not return a value.
Instead, define App as an object literal, as follows:
var App = {
showOccurenceFiltering: function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
};
Now your call will be valid.

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............

Categories