How to get external json (in my external files) to html list. Try to avoid jQuery in this question. Because I tried with json but the
$.getJSONis not working. So please try to answer me using Javascript. An in HTML List not HTML Table
Category: javascript
Category Added in a WPeMatico Campaign
Convert require() without assignment to import
file1.js
console.log("foo")
file2.js
require("./file1")
➜ node file2.js
foo
How would I convert file2.js’s require to import and keep the same logic (so no assignment)?
(Gatsby) Datawrapper iframes aren’t displaying before I’ve refreshed the page
I’m using Datawrapper to display graphs as iframes on my website.
I just recently migrated from Remark to MDX. With the new setup, my Datawrapper graphs aren’t loading before the page that contains the graphs is allowed to load in the “traditional” sense (i.e., hitting refresh or following the page that contains the graphs directly).
So, if you follow this link, the graphs display fine: kolstadmagnus.no/ekspert-mener-a-ha-svaret-bak-krfs-stortingssmell.
But if you go to the home page (kolstadmagnus.no) and then hit the link (second-top post), the graphs won’t display.
Some context
Datawrapper iframes use this script so that the iframes will be responsive:
!function(){"use strict";window.addEventListener("message",(function(e){if(void 0!==e.data["datawrapper-height"]){var t=document.querySelectorAll("iframe");for(var a in e.data["datawrapper-height"])for(var r=0;r<t.length;r++){if(t[r].contentWindow===e.source)t[r].style.height=e.data["datawrapper-height"][a]+"px"}}}))}();
Since Gatsby works the way it does (not loading every page “traditionally”—sorry, I don’t know what the feature is called), I have had to put this script in the html.js file, like this:
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
<script
dangerouslySetInnerHTML={{
__html: `
!function(){"use strict";window.addEventListener("message",(function(e){if(void 0!==e.data["datawrapper-height"]){var t=document.querySelectorAll("iframe");for(var a in e.data["datawrapper-height"])for(var r=0;r<t.length;r++){if(t[r].contentWindow===e.source)t[r].style.height=e.data["datawrapper-height"][a]+"px"}}}))}();
`,
}}
/>
</body>
</html>
This causes the script to be executed for the entire website instead of just for that single page, thereby solving the issue where hitting refresh would be required after entering the pages with the iframes.
Now though, with MDX, problems are back. But now the iframes don’t display at all.
How do I solve this?
Javascript : How to get result from axios request error? [duplicate]
I want to get result from the axios function, but not only when request is success, but also if failed.
How to make result as that err data? I know this is a sort of promise function, but this doesn’t work.
router.get('/test', async (req, res) =>{
let result = await axios.get('a/specific/url').catch((err) => {
Promise.resolve(err)
})
console.log('/test >>', result)
})
ChartJs in endless loop
I’ve got a just-created empty chart.js chart and it stucks in an animated endless loop. Why? What am I doing wrong?
var initData=
{
type: "polarArea",
data: {datasets:[]},
options: {
plugins: {},
responsive: true,
maintainAspectRatio: false,
scales: {
r: {}
}
}
};
var context = document.getElementById('test').getContext('2d');
var chart = new Chart(context, initData);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div><canvas style="margin: 0.5em; width: 100%; height: 20em" id="test"></canvas></div>
JavaScript function execution time
I wanted to test the execution time of console.log, but whatever number I set as the delay for setTimeout, it is still executed after console.log. I don’t understand why so.
function first() {
console.log("This should be printed first");
}
setTimeout(first, 0.00001);
console.log("This should be printed second");
React: declare functions inside render bad practice benchmark
According to the React community declare functions inside render method is a bad practice, as describe in this question: Is it bad to create functions in render?
For example:
export default function Clock({ time }) {
const hours = () => time.getHours();
const minutes = () => time.getMinutes();
const seconds = () => time.getSeconds();
const milliseconds = () => time.getMilliseconds();
return (
<h1>
{hours()}:{minutes()}:{seconds()}.{milliseconds()}
</h1>
);
}
I can guess, the functions defined will be recreated after every render, forcing Garbage Collector to clean this memory-leak. But actually that is the function of the GC, so I’m not really sure if that is the main issue.
Since I can’t find explicit documentation for describing why this is a bad practice I’m trying to create a benchmark to really test the performance, so I have created this two examples in codesandbox:
Bad practice:
https://codesandbox.io/s/render-with-function-inside-bad-practice-xx40g?file=/src/Clock.js
Good practice:
https://codesandbox.io/s/render-without-functions-good-practice-ckn1m?file=/src/Clock.js
I’m checking the react profiler but I can’t really tell the difference, and using the performance tool of chrome I can see a difference in “scripting”
But I don’t understand what this means.
I’m not sure if I’m doing the benchmark properly
How to add loader correctly while infinite scrolling?
I tried multiple ways to implement loading while I am fetching more data during infinite scrolling but nothing worked properly, so I deleted loader, I have here state (with redux) named: loading but cannot write the logic of loading correctly. Could you please tell me how can I make it work?
Here I will provide with code:
import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {setAllUsers, setLoading, setPage} from '../redux/actions/actions';
import User from './User';
import '../styles/AllUsersList.css';
const AllUsersList = () => {
const allUsers = useSelector(state => state.setAllUsersReducer);
const page = useSelector(state => state.setPageReducer);
const loading = useSelector(state => state.setLoadingReducer);
const dispatch = useDispatch();
const fetchAllUsers = () => {
fetch(`${url}/${page}/15`)
.then(res => res.json())
.then(data => {
dispatch(setAllUsers(data.list));
})
.catch(err => console.log('Error message: ', err))
}
useEffect(() => {
fetchAllUsers();
}, [page])
const handleScroll = () => {
dispatch(setPage());
}
window.onscroll = function () {
if(window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
handleScroll();
}
}
return (
<div className="allUsersList">
{
allUsers ? (
allUsers.map((user, index) => (
<Link key={user.id} to={`/user/${user.id}`}>
<User name={user.name} lastName={user.lastName} prefix={user.prefix} title={user.title} img={user.imageUrl}/>
</Link>
))
) : (
<div> Loading... </div>
)
}
</div>
)
}
export default AllUsersList;
In Moodle How do I allow a single student a second attempt on a quiz?
I am working in the moodle right now How do I allow a single student/Candidate/individual user a second attempt on a quiz?
Is there any possible way to do that because if I allow a quiz retake it may apply on a group level and every user can attempt quiz.
Javascript add new line to table and replace IDs
I’m a hobby coder and struggle with following issue:
I got a table element with a few rows, each row 3 cells. Via a button at the bottom I would like to add rows. The table looks like this:
<table id="mytable">
<tr id="line[0]"><td id="cellA[0]"</td><td id="cellB[0]"</td><td id="cellC[0]"</td></tr>
<tr id="line[1]"><td id="cellA[1]"</td><td id="cellB[1]"</td><td id="cellC[1]"</td></tr>
<tr id="line[2]"><td id="cellA[2]"</td><td id="cellB[2]"</td><td id="cellC[2]"</td></tr>
</table>
I loop through with elementbyID “line” to find that the last line is [2]. And then add a new line like this:
var table = document.getElementById("mytable");
var row = table.insertRow(oldID + 1);
row.setAttribute("id","line["+ oldID + 1 + "]");
This works great.
Next I get the content of the last line via var lastLine = document.getElementById(oldID).innerHTML. Now since the td IDs are cellA[2], cellB[2] and cellC[2]. I would like to replace those with [3].
I tried following:
var oldVar = "[" + oldID + "]";
var newVar = "[" + oldID + 1 + "]";
var regex = new RegExp(oldVar, "g");
var neueLine = lastLine.replace(regex, newVar);
but this results in ids like this “cellA[3][3]”, “cellB[3][3]” and “cellC[3][3]”.
I feel like my limited knowledge is missing out on the supposed way to do this.
Thanks a lot for your help!
Another way to write a labelled function?
Is there another way to write a labelled function.
I don’t understand when we use colon:
check**:** function(element){
let id=element.id.split('');
if(id[id.length-1]==this.questions[this.index].answer){
this.score++;
element.className="correct";
this.scoreCard();
MediaRecorder not woking on IOS
I am creating a website, which works on all desktop browsers (even Safari), and also on android phones, but when I try to open the site on an iphone, it shows the given error.
enter image description here
My mediaRecorder code is as follows
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
try {
recorder = new MediaRecorder(stream);
} catch (e) {
console.log(e);
alert(`Exception while creating MediaRecorder: ${e.toString()}`);
}
recorder.chunks = []
recorder.ondataavailable = e => {
recorder.chunks.push(e.data);
}
recorder.onstop = () => {
blob = new Blob(recorder.chunks);
}
recorder.onstart = () => {
mic_callbacks = {
'resume' : () => {
recorder.resume()
},
'pause' : () => {
recorder.pause()
}
}
}
recorder.start(1000)
recorder.pause()
}).catch(console.error);
if you want to see the error head on the website is located at https://hitokara.org.in/p/skyfall
Submitting AJAX Post to Body
I’m trying to submit a form using ajax and send the data from a textarea to the body of the post request.
<form method="post">
<textarea name="fkb_newdata" id="fkb_newdata" class="form-control mt-5" cols="30" rows="10">
data...
goes...
here...
</textarea>
<button class="btn btn-primary mt-2" type="submit" id="fkb_savedata">
Daten übernehmen
</button>
</form>
using javascript I prevent the default behaviour of the browser and submit the data to a c# endpoint.
$("#fkb_savedata").on("click", function() {
event.preventDefault();
somefunctiontopreparethedata();
$.ajax({
url: "/backend/apiendpoint",
type: "POST",
data: {
newdata: newdata // JSON.stringify(newdata)
},
dataType: "json",
success: function(res) {
// console.log(res);
$("#fkb_savedata").text("Daten wurden gespeichert");
$("#fkb_savedata").prop("disabled", true);
},
error: function(error) {
console.log('error');
}
});
});
with both data and newdata I have the issue that when I inspect with the network tab that the data looks like an array
e.g. for newdata:
Array ( [newdata] => Array ( [0] => Array ( [0] => 001086 [1] => 30.42 ) [1] => Array ( [0] => 001188 [1] => 30.42 ) ) )
and for JSON.stringify(newdata)
Array ( [newdata] => [["001086","30.42"],["001188","30.42"]] )
Formdata in The Payload Tab:
newdata: [["001086","30.42"],["001188","30.42"]]
Is there a simple way to transform this array to propper json format for submitting to the api endpoint?
thank you in advance!
mdbreact datatable pagination issue
Im using mdbreact package to display the data in a datatable. In the datatable I have a column with checkbox to change the value. When I check or Uncheck and move to the second page, the values of the checkbox in the second page is also changing. How do I sort this issue?
ReactNative & EXOP Error iOS Bundling failed 6ms Unable to resolve module
I am learning React Native and Expo. I trying to build an application that enables the user to log in using the phone number I have an issue “iOS Bundling failed 6ms Unable to resolve module ./screens/Phone Auth form ..”
I have been trying for almost a while to find a way to log in via the mobile number through Expo and React Native, but I have not found useful resources.
In all my attempts, many problems appear. I have tried several methods. Can I win from using the registration feature via the phone number?
App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PhoneAuth from './screens/PhoneAuth';
export default function App() {
return (
<View style={styles.container}>
<PhoneAuth/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
PhoneAuth.js
import React, { useRef, useState } from 'react';
import { TouchableOpacity, Text, TextInput, View } from 'react-native';
import { FirebaseRecaptchaVerifierModal } from 'expo-firebase-recaptcha';
import Constants from 'expo-constants';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
// other services is needed
// import styles from './styles';
const PhoneAuth = () => {
const [phoneNumber, setPhoneNumber] = useState('');
const [code, setCode] = useState('');
const [verificationId, setVerificationId] = useState(null);
const recaptchaVerifier = useRef(null);
const sendVerification = () => {
const phoneProvider = new firebase.auth.PhoneAuthProvider();
phoneProvider
.verifyPhoneNumber(phoneNumber, recaptchaVerifier.current)
.then(setVerificationId);
};
const confirmCode = () => {
const credential = firebase.auth.PhoneAuthProvider.credential(
verificationId,
code
);
firebase
.auth()
.signInWithCredential(credential)
.then((result) => {
console.log(result);
});
};
return (
<KeyboardAwareScrollView contentContainerStyle={styles.container}>
<View>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={Constants.manifest.extra.firebase}
/>
<TextInput
placeholder="Phone Number"
onChangeText={setPhoneNumber}
keyboardType="phone-pad"
autoCompleteType="tel"
style={styles.textInput}
/>
<TouchableOpacity
style={styles.sendVerification}
onPress={sendVerification}
>
<Text style={styles.buttonText}>Send Verification</Text>
</TouchableOpacity>
<TextInput
placeholder="Confirmation Code"
onChangeText={setCode}
keyboardType="number-pad"
style={styles.textInput}
/>
<TouchableOpacity style={styles.sendCode} onPress={confirmCode}>
<Text style={styles.buttonText}>Send Verification</Text>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
)
}
export default PhoneAuth;

