Need id in url from js - javascript

I need a script that fetch id from javascript into an url
For example: https://google.com/youtube[id].mp3
javascript currently:
$(document).ready(function() {
// FETCHING DATA FROM JSON FILE
$.getJSON("https://api.omny.fm/orgs/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/programs/a49c87f6-d567-4189-8692-a8e2009eaf86/clips/",function(data) {
$('#table').html(data.Clips[0].Id);
});
});
html currently:
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./style.css">
</head>
<meta http-equiv="refresh" content="0; url=https://traffic.omny.fm/d/clips/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/a49c87f6-d567-4189-8692-a8e2009eaf86/<p id="table">/audio.mp3" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="./script.js"></script>
</html>
i hope someone can help me out to get this working :)
thx.
tried multiple things to get id into url but not working

Your question is very unclear, but I assume what you're trying to do is fetch the JSON data, then append it to a table.
The first reason things aren't working is likely because your HTML is invalid. Specifically right here:
<!-- Why are you trying to embed a p tag into a link? -->
<meta http-equiv="refresh" content="0; url=https://traffic.omny.fm/d/clips/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/a49c87f6-d567-4189-8692-a8e2009eaf86/<p id="table">/audio.mp3" />
The second issue is that you're using the jQuery .html() method, which actually just sets the innerHTML of an element. This is dangerous, and you should not do this (especially with fetched data).
// This is not good for many reasons
$('#table').html(data.Clips[0].Id);
Also, why are you using jQuery in 2023? DOM APIs are modern and extensive nowadays. jQuery is nothing but an abstraction on top of them. Here's a solution I believe will help you.
const URI = 'https://api.omny.fm/orgs/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/programs/a49c87f6-d567-4189-8692-a8e2009eaf86/clips/';
const tableBody = document.querySelector('table > tbody');
const createCell = (content) => {
const cell = document.createElement('td');
cell.textContent = content;
return cell;
};
const createRow = (id, title) => {
const row = document.createElement('tr');
row.appendChild(createCell(id));
row.appendChild(createCell(title));
return row;
};
document.addEventListener('DOMContentLoaded', async () => {
// Use the native "fetch" API to fetch the data.
const res = await fetch(URI);
// Convert the data to JSON using the ".json()" method.
const json = await res.json();
// Loop through all of the clips in the received array.
for (const clip of json.Clips) {
// For each clip, add a new row to the table.
tableBody.appendChild(createRow(clip.Id, clip.Title));
}
});
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody></tbody>
</table>

Related

select data by clicking buttons, then combine associated CSVs into one array

I'm creating an interface where a user can click on buttons that have the names of CSVs in order to see the combined data they select charted.
I've set it up so that each button click adds the name of a CSV to an array (called chosenData). Then I'm using a for loop to cycle through the chosenData array, grab the data from github, and push all of the data into another array called allData.
However, the data doesn't combine correctly. I've been pulling my hair out over this problem for hours and haven't been able to resolve it, so any help would be greatly appreciated!
Code below. Here's also a jsfiddle
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>combine CSVs</title>
</head>
<body>
<button id="arr1" class="button">arr1</button>
<button id="arr2" class="button">arr2</button>
<button id="arr3" class="button">arr3</button>
<button id="arr4" class="button">arr4</button>
<button id="arr5" class="button">arr5</button>
<script>
var parseTime = d3.timeParse("%Y-%m")
let chosenData = []
let allData = []
$('.button').on('click', d => {
let data = event.target.id
console.log(data)
chosenData.push(data)
console.log('chosenData', chosenData)
obtainData(chosenData)
})
function obtainData(chosenData) {
for (i = 0; i < chosenData.length; i++) {
let arrayName = chosenData[i]
let dailyData = axios.get("https://raw.githubusercontent.com/sprucegoose1/sample-data/main/" + chosenData[i] + ".csv")
.then(content => {
let single = content.data
let singleCSV = d3.csvParse(single)
singleCSV.forEach(d => {
d.value = +d.value
d.interval = +d.interval
d.time = +d.time
d.code = arrayName
d.date = parseTime(d.date);
})
console.log('single data', singleCSV)
allData.push(singleCSV)
})
}
const merge = allData.flat(1);
chartData(merge);
}
function chartData(allData) {
console.log('all data', allData)
// create a chart with combined data here
}
</script>
</body>
</html>
The issue is probably that the fetches are async. You start them in the for loop, but you don't wait for them before you do the flattening and call chartData.
You could push the promises returned by axios.get in the loop to ann array, then after the loop use Promise.all to wait for all of them before you merge.

Can't get firebase to connect to HTML page

I'm working on the front end for a project to display a graph of data collected from sensors. I'm following Net Ninja's youtube series on connecting to firebase, as well as trying many other approaches found online, but nothing I try works. I cannot get data from my firebase test database to display, and also can't display example data from others. I was hoping for a bit of help in what I could have missed.
const dataList = document.querySelector('#data-list');
// create element & render data
function renderData(doc) {
let li = document.createElement('li');
let time = document.createElement('span');
let data = document.createElement('span');
li.setAttribute('data-id', doc.id);
time.textContent = doc.data().time;
data.textContent = doc.data().data;
li.appendChild(time);
li.appendChild(data);
dataList.appendChild(li);
}
// getting data
db.collection('sensorData').get().then(snapshot => {
snapshot.docs.forEach(doc => {
renderData(doc);
});
});
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-database.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>test</h1>
<div class="content">
<form id="add-data-form"></form>
<ul id="data-list"></ul>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = { **
FIREBASE DATA **
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
firebase.analytics();
</script>
<script src="app.js"></script>
</body>
</html>
When I launch the index, I only see the "test" heading, no data from the firebase. I have used powershell to initialise the database, that didn't make a difference though. Any help would be greatly appreciated, thank you

How can I fetch data from an API, process the data and render everything after the data was parsed?

My problem is that while fetching data from an API the website is already loaded, so for a second or so I see the default data in the elements and only after that the element data is updated.
I've already tried many ways like Async/Await and Promises and also events like jQuery.ready(), window.onload(), and the DOMContainerLoaded event on the fetch method but everytime, the page loads first.
In short, I want to (in order):
Get the data from an API (json)
Parse the data to an Object
Updated the elements on the page with the data
Render the whole page
This is what I have at the moment:
Player.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/public/js/classes.js" charset="utf-8"></script>
<script src="/public/js/player.js" charset="utf-8"></script>
</head>
<body>
<div class="container">
<img id="playerAvatar" class="avatar" alt="The avatar of the player">
<h2 id="nick"></h2>
<!-- More Stuff Later -->
</div>
</body>
</html>
player.js
window.addEventListener('DOMContentLoaded', async function(){
const player = await processPlayerData();
fillPlayerData(player);
});
async function processPlayerData(){
const user = new URLSearchParams(window.location.search).get('id');
const json = await requestData('/api/player/'+ user, {method: "GET"});
let player = new Player();
if("errors" in json)
player = null;
else
player.fillData(json);
return player;
}
async function requestData(dir, options) {
const response = await fetch(dir, options)
.then((response) => { return response.json(); });
return response;
}
function fillPlayerData(player){
if(player === null)
alert("The user does not exist!");
else{
document.getElementById('nick').innerHTML = "AlexMFV"; //player.nickname;
document.getElementById('playerAvatar').src = "https://media.gettyimages.com/photos/colorful-powder-explosion-in-all-directions-in-a-nice-composition-picture-id890147976?s=612x612"; //player.avatarUrl;
//Fill the elements with all the player data
//Get all player matches
}
return true;
}
And also on the server I have a method that is gathering the JSON from the API:
async function getPlayerData(req, res){
let value;
try{
const user = req.params.id;
value = await fetch(strPlayerData.replace('<usr>', user), packet).then((res) => { return res.json(); });
res.json(value);
}
catch(e){
error(res, e);
}
}
If there is something that you don't understand please tell me so that I can provide more information.
Edit: If you want to try it so that you can see what I mean, the project is available here: https://faceitstats.alexmfv.com/player.html?id=Alex

Why did fetch() API failed to retrieve custom HIBP JSON data?

I am trying to use the Have I Been Pwned? API to retrieve a list of breaches for a given email account.
I retrieve this list using the fetch() API. In the browser it looks like there is a connection to the HIBP website but the expected breaches are not visible.
I think this is a JSON problem because the API returns results without a root tree (?) (e.g. [breaches:{"Name"... - only the {"Name"}), so I think I'm making a mistake at the iteration step in the JS file. Also, I'm not calling the 'retrieve' function in the HTML file correctly because the browser throws an error: 'Uncaught ReferenceError: retrieve is not defined', but this is a side-issue (fetch('https://haveibeenpwned.com/api/v2/breachedaccount/test#example.com') doesn't work either).
This is my first week working with JS, fetch(), and JSON, so I consulted a couple of sources before asking this question (but I still can't figure it out, after a couple of days):
How to Use the JavaScript Fetch API to Get Data
fetch API
API methods for HaveIBeenPwnd.com (unofficial)
Where is the actual problem?
The index.html file:
<!DOCTYPE html>
<html lang=en>
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
</head>
<body id="top">
<header id="header">
<div class="content">
<h1 style="text-align: center">Put an email in this box</h1>
<input type="email" id="InputBox" value="" autocapitalize="off" spellcheck="false" />
<button type="submit" id="PwnedButton" onclick="retrieve">pwned?</button>
<ul id="results"></ul>
</div>
</header>
<script src="test.js"></script>
</body>
</html>
The test.js file (I know that JS is an interpreted language - so empty characters affect execution speed - but I made it more readable for this example):
function createNode(element) {
return document.createElement(element); // Create the type of element you pass in the parameters
}
function append(parent, el) {
return parent.appendChild(el); // Append the second parameter(element) to the first one
}
const account = document.getElementById('InputBox');
const PwnedButton = document.getElementById('PwnedButton');
const results = document.getElementById('results');
fetch('https://haveibeenpwned.com/api/v2/breachedaccount/' + account)
.then((resp) => resp.json()) // Transform the data into json
.then(function(retrieve) {
let breaches = retrieve.Name; // Get the results
return breaches.map(function(check) { // Map through the results and for each one run the code below
let span = createNode('span'); // Create the element we need (breach title)
span.innerHTML = `${breaches}`;
append(results, span);
})
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
let breaches = retrieve.Name;
retrieve is not an object with a Name property.
It is an array containing multiple objects, each of which has a Name property.
You have to loop over it.
e.g.
retrieve.forEach( item => {
let breaches = retrieve.Name;
console.log(breaches);
});
breaches.map
… and the Name is a string, so you can't map it. You can only map an array (like the one you have in retrieve).
I have created working version of what are you possible going to implement, taking Name field from result. https://jsfiddle.net/vhnzm1fu/1/ Please notice:
return retrieve.forEach(function(check) {
let span = createNode('span');
span.innerHTML = `${check.Name}<br/>`;
append(results, span);
})

Clickstream Tracking in Veeva CRM

I am working with Veeva CRM, trying to use Click Stream Tracking. I have the code which I am using and trying to track the Presentation id, Product Key Message, track an Element Description and Answer.
Can anybody help with the code that I am using.
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CLM_CERT_HCPName</title>
<!-- Bootstrap -->
<link href="css/style.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<script src="js/veeva-library-3.0.js"></script>
<script>
function start(){
header_getAccountName();
}
function header_getAccountName(){ com.veeva.clm.getDataForCurrentObject("Account","Name",header_displayAccountName)}
function header_displayAccountName(result){
var AccountNameHTML = document.getElementById("hcpName");
AccountNameHTML.innerHTML += result.Account.Name;com.veeva.clm.getDataForCurrentObject("Presentation","Survey_vod__c",header_getSurveyID);
}
function mySaveObject(){
//This is the start of my JSON object
var myCallClickStream = {Call_vod__c, Key_Message_vod__c};
//i am using my JSON obj name with the field API name of the call clickstream object obj.apiName then set the value. obj.apiName= value;]
// Create the record using the com.veeva.clm.createRecord
com.veeva.clm.createRecord("Call_ClickStream_vod_c", myCallClickStream, printSavedResults)}
function printSavedResults(result){
alert(JSON.stingify(result));
}
</script>
</head>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
I have also some sample code to try out but not sure what I am doing wrong.
function mySaveObject(){
var myCallClickStream = {};
myCallClickStream.Text_Entered_vod__c = "i will put some text here";
com.veeva.clm.createRecord("Call_Clickstream_vod__c", myCallClickStream, printSavedResults)
}
function printSavedResults(result) {
alert(JSON.stringify(result));
}
Not sure if you still need help on this or not. But my team uses a simple method in every project to simplify the tracking process. The below was modified to fit some of your naming conventions/needs.
// clmDescription - string submitted as the description to be tracked
// clmAnswer - string submitted as the answer to be tracked`
// callback - call back function which will be used to return the information
function mySaveObject( clmDescription, clmAnswer, clmCallback ) {
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/') + 1),
clmTrackingID = filename.replace(".html", "");
var myCallClickStream = {};
myCallClickStream.Track_Element_Id_vod__c = clmTrackingID;
myCallClickStream.Track_Element_Type_vod__c = clmDescription;
myCallClickStream.Selected_Items_vod__c = clmAnswer;
myCallClickStream.Track_Element_Description_vod__c = clmAnswer;
// var myJSONText = JSON.stringify( myCallClickStream );
com.veeva.clm.createRecord( Call_Clickstream_vod__c, myCallClickStream, clmCallback );
}
Simply call the method and pass in your parameters, including your callback method.
Hope this helps!

Categories

Resources