How to assign a JS variable to a JSON route - javascript

So I'm coding this
https://vercel.com/eduardodevolmedo/jsd-aily
function executeWeekly() {
fetch("/data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
currentW = data[0].timeframes.weekly.current
previousW = data[0].timeframes.weekly.previous
currentWork.innerHTML = `${currentW}${hrs}`
previousWork.innerHTML = `${lastWeek} - ${previousW}${hrs}`
//DATA FROM PLAY
currentP = data[1].timeframes.weekly.current
previousP = data[1].timeframes.weekly.previous
currentPlay.innerHTML = `${currentP}${hrs}`
previousPlay.innerHTML = `${lastWeek} - ${previousP}${hrs}`
//DATA FROM STUDY
currentS = data[2].timeframes.weekly.current
previousS = data[2].timeframes.weekly.previous
currentStudy.innerHTML = `${currentS}${hrs}`
previousStudy.innerHTML = `${lastWeek} - ${previousS}${hrs}`
//DATA FROM EXERCISE
currentE = data[3].timeframes.weekly.current
previousE = data[3].timeframes.weekly.previous
console.log(currentE, previousE)
currentExercise.innerHTML = `${currentE}${hrs}`
previousExercise.innerHTML = `${lastWeek} - ${previousE}${hrs}`
//DATA FROM SOCIAL
currentSO = data[4].timeframes.weekly.current;
previousSO = data[4].timeframes.weekly.previous;
currentSocial.innerHTML = `${currentSO}${hrs}`
previousSocial.innerHTML = `${lastWeek} - ${previousSO}${hrs}`
//DATA FROM SELFCARE
currentSE = data[5].timeframes.weekly.current;
previousSE = data[5].timeframes.weekly.previous;
currentSelfcare.innerHTML = `${currentSE}${hrs}`
previousSelfcare.innerHTML = `${lastWeek} - ${previousSE}${hrs}`
})
eachBlock.forEach(el => el.classList.toggle('animatedBox'))
}
function executeDaily() {
fetch("/data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
//DATA FROM WORK
currentW = data[0].timeframes.daily.current
previousW = data[0].timeframes.daily.previous
currentWork.innerHTML = `${currentW}${hrs}`
previousWork.innerHTML = `${lastDay} - ${previousW}${hrs}`
//DATA FROM PLAY
currentP = data[1].timeframes.daily.current
previousP = data[1].timeframes.daily.previous
currentPlay.innerHTML = `${currentP}${hrs}`
previousPlay.innerHTML = `${lastDay} - ${previousP}${hrs}`
//DATA FROM STUDY
currentS = data[2].timeframes.daily.current
previousS = data[2].timeframes.daily.previous
currentStudy.innerHTML = `${currentS}${hrs}`
previousStudy.innerHTML = `${lastDay} - ${previousS}${hrs}`
//DATA FROM EXERCISE
currentE = data[3].timeframes.daily.current
previousE = data[3].timeframes.daily.previous
currentExercise.innerHTML = `${currentE}${hrs}`
previousExercise.innerHTML = `${lastDay} - ${previousE}${hrs}`
//DATA FROM SOCIAL
currentSO = data[4].timeframes.daily.current;
previousSO = data[4].timeframes.daily.previous;
currentSocial.innerHTML = `${currentSO}${hrs}`
previousSocial.innerHTML = `${lastDay} - ${previousSO}${hrs}`
//DATA FROM SELFCARE
currentSE = data[5].timeframes.daily.current;
previousSE = data[5].timeframes.daily.previous;
currentSelfcare.innerHTML = `${currentSE}${hrs}`
previousSelfcare.innerHTML = `${lastDay} - ${previousSE}${hrs}`
})
eachBlock.forEach(el => el.classList.toggle('animatedBox'))
}
So, im running the exact same function at monthly, and daily.
Which is now working, but i had to copy the same code for the same functions, so I was thinking in a way I could do it in less lines of code. So, my idea was to assign a string to a variable, and then making it a string, using JSON.stringify()
let z = weekly
let x = JSON.stringify(z)
Then i thought, that I would assing a variable to each button on html, using an if statement, for example if the button value was "daily" then z would be daily, and the function would run using daily as that argument.
And then, I just add it like a variable, depending on what i want:
currentW = data[0].timeframes.z.current
instead of:
currentW = data[0].timeframes.daily.current
In that way, I would only need to use one function.
But that doesn't seems to work.
How can I do this? Is there any way?
If you want to check the code further:
https://github.com/EduardoDevOlmedo/JSDaily

You have to access the object member as if the object was an associative array:
currentW = data[0].timeframes[z].current

Solved:
Accessing to
this.innerHTML
and assigning the value to z.
function check(){
value = this.innerHTML
execute(value)
}

Related

Incomplete response received from application Error

I am doing a virtual pos integration, in the second part of the step, I have to post the data I received from the user to the specified field, for this I had to get some information from the database, I am pulling data with 2 different intertwined queries, and then I am posting the data, but I am getting an error:
Incomplete response received from application
const reqUrl = 'https://onlineodeme.vakifbank.com.tr:4443/VposService/v3/Vposreq.aspx?prmstr='
Server.getAllData('paytr') // get data from paytr collection
.then((result) =>{
var uniqueId = req.body.VerifyEnrollmentRequestId.split(',')[0]
var uniqueId2 = req.body.VerifyEnrollmentRequestId
var newUniqueId = new Date().getTime()
var uyeNumarasi = encryptedData.decrypt(result[0].merchant_id) //merchant
var uyeSifresi = encryptedData.decrypt(result[0].merchant_salt)//merchant
var teminalNo = encryptedData.decrypt(result[0].merchant_key)//merchant
var amountResult = req.body.PurchAmount / 100
const amount = amountResult + '.00'
var resBrandName = '300' // troy
if(req.body.Pan.startsWith('4') ){resBrandName = '100'} //visa
if(req.body.Pan.startsWith('5') ){resBrandName = '200'} // mastercard
var resCreditCardNumber = req.body.Pan
var ResCurrencyCode = req.body.PurchCurrency
var resExpiryData = req.body.Expiry
var clientIp = 'xx.xxx.xx.xx' //req.body.SessionInfo.ipAdress
var CAVV = req.body.Cavv
var eci = req.body.Eci
Server.findPayments(parseInt(uniqueId))// get data by unique id
.then((data) =>{
const CVV = encryptedData.decrypt(data.CVV)
const cardanmeSurname = data.cardNameSurname
var sendUrl = `Cvv=${CVV}&TransactionDeviceSource=0&MpiTransactionId=${uniqueId2}&ECI=${eci}&CAVV=${CAVV}&ClientIp=${clientIp}&CardHoldersName=${cardanmeSurname}&Expiry=${resExpiryData}&TransactionType=Sale&MerchantId=${req.body.MerchantId}&Password=${uyeSifresi}&TransactionId=${newUniqueId}&TerminalNo=${teminalNo}&CurrencyCode=${ResCurrencyCode}&CurrencyAmount=${amount}&BrandName=${resBrandName}&Pan=${resCreditCardNumber}`
axios.post(reqUrl , sendUrl,
{
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then((dataUrl) =>{
console.log(dataUrl)
res.send('veri var usta axios')
})
.catch((err) => {
res.send('hata var usta axios')
console.log(err)
})
})
})
I am making the request on hosting but unfortunately I did not get any results, thanks in advance for your help.

Assigning variable in javascript error returns undefined

I don't know if this is a glitch or a mistake that I made. But I use console.log(record) this is the result
accountRateId: 6
effectiveEndDate: "2019-09-30T00:00:00"
effectiveStartDate: "2019-09-01T00:00:00"
rate: 100
I have this code to assign the variables
let rate = record.rate;
let effectiveStartDate = record.effectiveStartDate;
let effectiveEndDate = record.effectiveEndDate;
console.log(rate);
but console.log(rate) returns undefined. Can anyone help me with this?
Update:
This is the code from the api
[Authorize("ADMIN")]
[HttpGet("Update/{id}")]
public IActionResult GetUpdate([FromQuery]QueryPagingParametersForNotes inParameters, int id)
{
List<object> rateList = new List<object>();
var rateListQueryResults = Database.AccountRates.Where(rate => rate.AccountRateId == id);
foreach (var oneRate in rateListQueryResults)
{
rateList.Add(new
{
accountRateId = oneRate.AccountRateId,
rate = oneRate.RatePerHour,
effectiveStartDate = oneRate.EffectiveStartDate,
effectiveEndDate = oneRate.EffectiveEndDate,
});
}
return new JsonResult(rateList);
}
This is the the code in javascript
$.ajax({
method: 'GET',
url: '/API/AccountRates/Update/' + inId
}).done(function (data) {
let record = data;
console.log(record);
let rate = record.rate;
let effectiveStartDate = record.effectiveStartDate;
let effectiveEndDate = record.effectiveEndDate;
console.log(rate);
console.log(effectiveStartDate);
//Populate the respective input controls with the lesson details.
$('#rateInput').val(rate);
$('#startDateInput').val(effectiveStartDate);
$('#endDateInput').val(effectiveEndDate);
})

Max value from 4 json source url

I have fetch some value from json url, with this
$(document).ready(function () {
function price(){
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
});
$.getJSON('trade/libs/bittrex.php?i=nxt', function(data){
document.getElementById('BittrexLastNXT').innerHTML = (data.Bittrex);
document.getElementById('BittrexBidNXT').innerHTML = (data.BittrexBid);
document.getElementById('BittrexAskNXT').innerHTML = (data.BittrexAsk);
});
$.getJSON('trade/libs/hitbtc2.php?i=NXT', function(data){
document.getElementById('HitbtcLastNXT').innerHTML = (data.hitbtc);
document.getElementById('HitbtcBidNXT').innerHTML = (data.hitbtcbid);
document.getElementById('HitbtcAskNXT').innerHTML = (data.hitbtcask);
});
$.getJSON('https://vip.bitcoin.co.id/api/nxt_btc/ticker', function(data) {
document.getElementById('priceLastNXT').innerHTML = (data.ticker.last);
document.getElementById('priceLashBuyNXT').innerHTML = (data.ticker.buy);
document.getElementById('priceLashSellNXT').innerHTML = (data.ticker.sell);
document.title = "NXT " + (data.ticker.last);
});
}
setInterval(price, 3000);
});
can I do this
function getMax(array){
return Math.max.apply(Math,array);
}
var NxtBid = document.getElementById("PoloniexBidNXT");
var NxtBid2 = document.getElementById("BittrexBidNXT");
var NxtBid3 = document.getElementById("HitbtcBidNXT");
var NxtBid4 = document.getElementById("priceLashBuyNXT");
var NxtBid5 = [NxtBid, NxtBid2, NxtBid3, NxtBid4];
var NxtBid6 = getMax(NxtBid5);
document.getElementById("NxtBidMax").innerHTML = NxtBid6;
I want to set low price and hi price from PoloniexLastNXT, BittrexLastNXT,HitbtcLastNXT, priceLastNXT.someone can help me
For Poloneix you can use assuming you have elements for "PoloniexLowNXT" and "PoloniexHighNXT",
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
document.getElementById('PoloniexLowNXT').innerHTML = (data.BTC_NXT.low24hr);
document.getElementById('PoloniexHighNXT').innerHTML = (data.BTC_NXT.high24hr);
});
You could try Promise.all and do a forEach on the results. Instead of repeating the implementation code you could create an array of settings and loop over it to get the result and process them:
const settings = [
[
"https://poloniex.com/public?command=returnTicker",//url
["#PoloniexLastNXT","#PoloniexBidNXT","#PoloniexAskNXT"],//elements to set
[//how to get value
data=>data.BTC_NXT.last,
data=>data.BTC_NXT.highestBid,
data=>data.BTC_NXT.lowestAsk
]
]
//others
];
Promise.all(
settings.map(
([url],index)=>
$.getJSON(setting(url))
.then(
data=>[data,settings[index]]
)
)
).then(
results=>{
var lowestLast=Infinity,highestLast=-Infinity;
results.forEach(
([data,[url,querySelectors,getters]])=>{
querySelectors.forEach(
(querySelector,index)=>
document.querySelector(querySelector).innerHTML=getters[index](data)
)
const last = getters[0](data);
if(last<lowestLast){
lowestLast=last;
}
if(last>highestLast){
highestLast=last;
}
}
)
return [lowestLast,highestLast];
}
).then(
([lowest,highest])=>{
console.log("lowest:",lowest,"highest:",highest);
}
).catch(
err=>console.warn("something went wrong:",err)
);
update
If you want to continue using your own repetitive implementation then you can get min and max in this way:
const numbers = [
new Number(trim(document.getElementById("PoloniexBidNXT").innerText)),
new Number(trim(document.getElementById("BittrexBidNXT").innerText)),
new Number(trim(document.getElementById("HitbtcBidNXT").innerText)),
new Number(trim(document.getElementById("priceLashBuyNXT".innerText)))
];
const lowest = Math.max.apply(null,numbers);
const highest = Math.min.apply(null,numbers);

Value changes when returned in an Angular 1.x Factory

Having a really weird problem with Angular and wondering if anyone has encountered this.
var transformResponse = function(data) {
var jobs = data.job.map(convertResponseToJob);
console.log(jobs);
// return jobs;
}
This logs the correct array with all the values within it, but this logs an array of the same length with undefined as each value.
var transformResponse = function(data) {
var jobs = data.job.map(convertResponseToJob);
console.log(jobs);
return jobs;
}
This may be something really obvious as I haven't worked with Angular factories very much, but I couldn't find an explanation.
Other Functions:
function convertResponseToJob(response){
var jobObj = new Job(response.id, response.clientId, response.book);
jobObj.bookName = response.book.name;
jobObj.submitDate = response.createDate;
jobObj.priority = response.priority;
jobObj.status = response.status;
jobObj.sequence = response.seqOrder;
return jobObj;
}
function Job(jobId, client, book) {
this.jobId = jobId;
this.client = client;
this.book = book;
this.bookName = null;
this.submitDate = null;
this.priority = 2;
this.sequence = 2;
this.status = null;
}

Pass variable to anon function / callback

I am trying to pass product into the find() function that contains a .toArray() anonymous function containing both error and array. Unfortunately this entire find() function runs within an iteration and only the first value goes in. How do I pass product to the callbacks?
var find = function(product,callbacks){
foos.find({
"foo": product.bars,
}).toArray(function (error, array) {
if(error){
callbacks.error(product,error);
} else if (array.length == 0) {
callbacks.none(product);
} else {
callbacks.exists(product);
}
});
}
Before this function i was processing products with forEach() then had this run in a callback within that. This was big trouble. Processed products with a regular for and now it works.
Old code
var products = function(data,callback){
products.forEach(function(product){
insert.product_id = product.id;
var variants = product.variants;
variants.forEach(function(variant){
insert.sku = variant.sku;
insert.variant_id = variant.id;
return callback(insert);
});
});
}
New code
var products = function(data){
var insert = [];
var products = data.products;
for(var pKey in products){
var product = products[pKey];
var variants = product.variants;
var set = {}
set.product_id = product.id;
for(var vKey in variants){
var variant = variants[vKey];
set.sku = variant.sku;
set.variant_id = variant.id;
insert.push(set);
}
}
return insert;
}

Categories