Javascript get method and airtable - javascript

Hye i am having a little trouble again i am supposed to put a list of questions in airtable and then print them to my screen but i am working with a fetch reqeust en then e method of get but i have the feeling like my empty variable aren't being filled with my questions
its in javascript btw :
here's my code :
; (function (){
window.addEventListener('load', function(){
document.getElementById('next').addEventListener('click', function(){
window.location.href = 'vragenlijst2.html';
})
let vrg1 = document.getElementById('1vraag');
let vrg2 =document.getElementById('2vraag');
let vrg3 = document.getElementById('3vraag');
let vrg4 = document.getElementById('4vraag');
let vrg5 = document.getElementById('5vraag');
let vrg6 = document.getElementById('6vraag');
let vrg7 = document.getElementById('7vraag');
let vrg8 = document.getElementById('8vraag');
let vrg9 = document.getElementById('9vraag');
let vrg10 = document.getElementById('10vraag');
let Vragenlijst_id = 1;
let getData = function(){
fetch('https://api.airtable.com/v0/appojP2iMG4i3P61S/EDBL', {
method: 'GET',
headers: {
'Authorization' : 'Bearer keyDhD8sLGjcEuA4K'
}
})
.then(Response => Response.json())
.then(JSON => {
console.log(JSON)
for(let index = 0; index < JSON.records.length; index++){
let Qstn = JSON.records[index];
if(Vragenlijst_id === Qstn.fields.vragenlijst){
let vrg1_db = Qstn.fields.Vraag1;
let vrg2_db = Qstn.fields.Vraag2;
let vrg3_db = Qstn.fields.Vraag3;
let vrg4_db = Qstn.fields.Vraag4;
let vrg5_db = Qstn.fields.Vraag5;
let vrg6_db = Qstn.fields.Vraag6;
let vrg7_db = Qstn.fields.Vraag7;
let vrg8_db = Qstn.fields.Vraag8;
let vrg9_db = Qstn.fields.Vraag9;
let vrg10_db = Qstn.fields.Vraag10;
vrg1 = vrg1_db;
vrg2 = vrg2_db;
vrg3 = vrg3_db;
vrg4 = vrg4_db;
vrg5 = vrg5_db;
vrg6 = vrg6_db;
vrg7 = vrg7_db;
vrg8 = vrg8_db;
vrg9 = vrg9_db
vrg10 = vrg10_db;
console.log(vrg1);
}
}
})
}
getData();
function create (){
let par = document.createElement('p');
par.innerHTML = vrg1;
document.getElementById('1vraag').appendChild(par);
}
document.getElementById('1vraag').innerHTML = create()

Related

prevent appen the exists data in ajax laravel chat

i have a ajax chat with laravel and every thing going okay when i open the chat but when i get new message the all old message repeated too , so i write a statement to prevent that because the normal is when i enter the page the chat load all old messages and when come any new message should append it not append the all old messages
if(chat_history.childElementCount !== data.messages.length)
but when i send any new message the statement will be false so what's solution here please
function getMessages(route,theTeacher) {
let chat_history = document.querySelector('#chat_history');
let options = {
method: 'GET',
headers: {
'Content-Type':
'application/json;charset=utf-8',
'X-CSRF-TOKEN':
document.head.querySelector("[name=csrf-token]").content
},
}
fetchRes = fetch(`${route}/${theTeacher}`, options);
fetchRes.then((response) => {
return response.json()
})
.then((data) => {
if(chat_history.childElementCount !== data.messages.length)
{
for (let c in data.messages) {
if(data.messages[c].sender.indexOf('admin') > -1) {
let liTwo = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let my_messages = document.createElement("div");
liTwo.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
my_messages.classList.add('message', 'my-message');
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data.innerHTML = message_data_span.outerHTML;
my_messages.innerText = data.messages[c].message;
liTwo.appendChild(message_data);
liTwo.appendChild(my_messages);
chat_history.append(liTwo);
// message_data_img.src = d
}
if (data.messages[c].sender.indexOf('teacher') > -1) {
let li = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let message_data_img = document.createElement("img");
let other_message = document.createElement("div");
li.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
other_message.classList.add('message','other-message', 'float-right')
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data_img.src = 'http://127.0.0.1/twaqah-project/twaqah/public/storage/' + data.teacher.avatar;
message_data.innerHTML = message_data_span.outerHTML + message_data_img.outerHTML;
other_message.innerText = data.messages[c].message;
li.appendChild(message_data);
li.appendChild(other_message);
chat_history.append(li);
// message_data_img.src = d
}
}
}
});
}
the blade code
setInterval(function() {
getMessages('{{route('chat.teacher-get-messages')}}',{{request()->teacher}});
}, 3000);

Updating a value in firebase with javascript not working

I have the following function to get and display data from firebase, create buttons to change the value of 'read' from a book
function readBooksSaved() {
firebase.database().ref('books').orderByChild('author').on('value', function(snapshot){
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
//alert(childData)
let key = childSnapshot.key
let b_title = childSnapshot.val().title;
let b_author = childSnapshot.val().author;
let b_page = childSnapshot.val().page;
let b_read = childSnapshot.val().read;
const u = document.querySelector('#container-li');
let a = document.createElement('li');
let b = document.createElement('li');
let c = document.createElement('li');
let d = document.createElement('li');
const li = document.createElement('li');
const button = document.createElement('a')
const button2 = document.createElement('a')
a.innerHTML = `<strong>Title:</strong> ${b_title}`;
b.innerHTML = `<strong>Author:</strong> ${b_author}`;
c.innerHTML = `<strong>Pages:</strong> ${b_page}`;
button.innerHTML = `Erase`;
if (b_read) {
b_read = 'Yes'
status = 'Unread'}
else {
b_read = 'No' }
d.innerHTML = `<strong>Read</strong> ${b_read}`;
button2.innerHTML = `<a class="btn btn-primary" id="change">${status}</a>`;
u.appendChild(a).classList.add("bg-info");
u.appendChild(b).classList.add("list-group-item");
u.appendChild(c).classList.add("list-group-item");
u.appendChild(d).classList.add("list-group-item");
u.appendChild(button).classList.add("list-group-item");
u.appendChild(button2).classList.add("list-group-item");
let change_bt = document.querySelector('#change')
change_bt.addEventListener('click', changeReadStatus(key, b_read))
});
});
}
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key)
if (b_read) {
db_firebase.update({'/read': false})
}
else {
db_firebase.update({'/read': true})
}
}
Everytime the page loads it enters to the changeReadStatus function and when click on the button the value or 'read' doesn't change on firebase. ¿Could you help me, please? I think I have some errors on the code but I have try without success.
Try this code:
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key);
if(b_read){
db_firebase.update({
'read': true
});
}
else{
db_firebase.update({
'read': false
});
}
}
You should be using the set() function, like this:
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key);
db_firebase.set({'read': b_read});
}

Async await on rendering component react

the js code below performs the loading of a series of fields remotely and then displays them on a map, the problem is that it calls it does not wait for the await and I proceed so the data is not displayed on the map which is redirected by the component , how can I do to make the chaima wait for the response of the function before proceeding to render the map
import {getmarcaturegiornaliere} from "module.js";
MyComponent.js
class Am4chartMap extends Component {
async componentDidMount() {
let map = am4core.create("map", am4maps.MapChart);
//Load values from response this function->
var marcature=await getmarcaturegiornaliere();
map.geodata = am4geodata_usaHigh;
map.percentHeight = 90;
map.dy = 10;
let polygonSeries = map.series.push(new am4maps.MapPolygonSeries());
polygonSeries.useGeodata = true;
map.homeZoomLevel = 1.2;
map.zoomControl = new am4maps.ZoomControl();
map.zoomControl.layout = 'horizontal';
map.zoomControl.align = 'left';
map.zoomControl.valign = 'bottom';
map.zoomControl.dy = -10;
map.zoomControl.contentHeight = 20;
map.zoomControl.minusButton.background.fill = am4core.color("#C7D0FF");
map.zoomControl.minusButton.background.stroke = am4core.color("#6979C9");
map.zoomControl.minusButton.label.fontWeight = 600;
map.zoomControl.minusButton.label.fontSize = 22;
map.zoomControl.minusButton.scale = .75;
map.zoomControl.minusButton.label.scale = .75;
map.zoomControl.plusButton.background.fill = am4core.color("#C7D0FF");
map.zoomControl.plusButton.background.stroke = am4core.color("#6979C9");
map.zoomControl.plusButton.label.fontWeight = 600;
map.zoomControl.plusButton.label.fontSize = 22;
map.zoomControl.plusButton.label.align = "center";
map.zoomControl.plusButton.scale = .75;
map.zoomControl.plusButton.label.scale = .75;
map.zoomControl.plusButton.dx = 5;
let plusButtonHoverState = map.zoomControl.plusButton.background.states.create("hover");
plusButtonHoverState.properties.fill = am4core.color("#354D84");
let minusButtonHoverState = map.zoomControl.minusButton.background.states.create("hover");
minusButtonHoverState.properties.fill = am4core.color("#354D84");
let polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#474D84");
polygonTemplate.stroke = am4core.color("#6979C9")
let hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#354D84");
let citySeries = map.series.push(new am4maps.MapImageSeries());
citySeries.data = marcature;
citySeries.dataFields.value = "size";
let city = citySeries.mapImages.template;
city.nonScaling = true;
city.propertyFields.latitude = "latitude";
city.propertyFields.longitude = "longitude";
let circle = city.createChild(am4core.Circle);
circle.fill = am4core.color("#C7D0FF");
circle.strokeWidth = 0;
let circleHoverState = circle.states.create("hover");
circleHoverState.properties.strokeWidth = 1;
circle.tooltipText = '{tooltip}';
circle.propertyFields.radius = 'size';
this.map = map;
}
componentWillUnmount() {
if(this.map) {
this.map.dispose();
}
}
render() {,.
module.js
//Setup server
import server from "./settings";
//Rest call axios module
const axios = require('axios').default;
export function getmarcaturegiornaliere() {
var date="03-02-2021";
console.log("Data: "+date);
var listmarcature=[];
axios.post(server.url+'/Utente/CaricamentoStoricoGiornonaliero', {
Data: date,
IdUtente: '3',
CalcoloOreGiornaliere: true
})
.then(function (response) {
console.log("Response: "+response.data);
//Vado ad iterare la response
let data = response.data;
for (let index in data){
console.log("Stato: "+data[index].Longitudine);
var datatemp={
"latitude" : data[index].Latitudine,
"longitude" : data[index].Longitudine,
"size" : 5,
"tooltip" : data[index].Stato,
};
listmarcature.push(datatemp);
}
}).catch(function (error) {
console.log("Errore: "+error);
});
return listmarcature;
}
Your function getmarcaturegiornaliere is not async, and this is the problem.
It will always return you an empty array [], because the return listmarcature; is executed before the .then() is. Therefore you return an empty array, and somewhere in the future the .then() will happen (and it will do nothing because you already returned).
The solution would be: Make it async.
There are some syntaxes available for that, I will bring you the best for this case:
Put async in the funciton: export async function getmarcaturegiornaliere() {
Add await before the axios call: await axios.post(...)

How can i collect all the data from the name value so i can use it?

let inpPas = document.querySelector('#inpPas');
let btnGo = document.querySelector('#btnGo');
const db = firebase.database();
let ref = db.ref('xVerdi');
let rootRef = firebase.database().ref().child('xVerdi');
rootRef.on('child_added', snap => {
let name = snap.child('name').val();
btnGo.onclick = goPassword;
function goPassword(){
if (inpPas.value == name) {
alert("yeyeye")
}
console.log("her " + name)
}
console.log(name)
})
I want to use all the data that i have stored in this name: value, but i can only use the most resent one. Any suggestions?
Do the following:
let nameList = [];
let rootRef = firebase.database().ref().child('xVerdi');
rootRef.on('child_added', snap => {
let name = snap.child('name').val();
nameList.push(name);

Multithread node.js instagram parser

Working on node.js instagram parser. At the moment I have 1 thread with proxy working code, but I'm not sure how to make multithread architecture:
'use strict';
var InstagramPrivateAPI = {};
InstagramPrivateAPI = {};
InstagramPrivateAPI.V1 = require(__dirname + '/client/v1');
InstagramPrivateAPI.Helpers = require(__dirname + '/helpers');
var acc = require(__dirname + "/client/v1/account");
var med = require(__dirname + "/client/v1/media")
var Promise = require('../bluebird');
var _ = require('../lodash/');
module.exports = InstagramPrivateAPI;
var Client = require('instagram-private-api').V1;
var device = new Client.Device('maksgmn');
var storage = new Client.CookieFileStorage(__dirname + '/cookies/maksgmn.json');
var session = new Client.Session(device, storage);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var fs = require('fs');
var proxyArray = fs.readFileSync('proxy.txt').toString().split("\n");
var usernamesArray = fs.readFileSync('usernames.txt').toString().split("\n");
var proxy = "http://" + proxyArray[getRandomInt(0,proxyArray.length)]
var username = usernamesArray[getRandomInt(0,usernamesArray.length)]
console.log(proxy)
console.log(username)
Client.Request.setProxy(proxy);
acc.searchForUser(session, username) //поиск id пользователя
.then(function(profile) {
return profile.id
})
.then(function(someId) { //получение промиса lenta
var feed = new Client.Feed.UserMedia(session, someId);
var lenta = Promise.mapSeries(_.range(0, 1), function() {
return feed.get();
}).then(function(lenta) {
return {id: someId, fd : lenta}
})
return lenta
})
.then(function(results) { //обработка промиса и получение ленты пользователя
// result should be Media[][]
var media1 = _.flatten(results.fd);
var urls1 = _.map(media1, function(medium) {
//var arr1 = medium.params.images[0].url;
var arr1 = []
try {
arr1 = medium.params.images[0].url
} catch (err) {
//console.log("lala")
}
return arr1;
//console.log(medium.params.carouselMedia.images[0].url)
})
//console.log(urls1)
return {id : results.id, linksNoCarousel : urls1, med : media1}
})
.then(function(res){
var urls2 = _.map(res.med, function(medium) {
var arr2 = []
try {
arr2 = medium.params.images[0][0].url
//console.log(arr2)
} catch (err) {
}
return arr2
})
for (var i = 0; i < 5; i++) {
if (typeof res.linksNoCarousel[i] == "undefined")
res.linksNoCarousel[i] = urls2[i];
}
var arr3 = []
for (var i = 0; i < 5; i++) {
arr3[i] = res.linksNoCarousel[i]
}
return {id : res.id, links : arr3}
})
.then(function(mediaAndId) {
acc = acc.getById(session, mediaAndId.id)
.then(function(account) {
//console.log(account.params)
let avatar = account.params.profilePicUrl;
let fullName = account.params.fullName;
let bio = account.params.biography;
let media0 = mediaAndId.links[0];
let media1 = mediaAndId.links[1];
let media2 = mediaAndId.links[2];
let media3 = mediaAndId.links[3];
let media4 = mediaAndId.links[4];
console.log(avatar);
console.log(fullName);
console.log(bio);
console.log(media0);
console.log(media1);
console.log(media2);
console.log(media3);
console.log(media4);
})
})
I would like it to work like multithread to be much more faster with proxies. As far as I'm working with node.js 2nd day, asking that question: how to do that?

Categories

Resources