How can I Show a API output number in HTML - javascript

See I want to make an HTML file that will display the current USD-GBP,
I am using this site: currencylayer.com
Their api :
http://apilayer.net/api/live?access_key=YOU_KEY_HERE&currencies=BBP&source=USD&format=1
Gives Me this output:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1522395543,
"source":"USD",
"quotes":{
"USDGBP":0.71
}
}
I Need an HTML file that Just displays 0.71.
Thank You In Advance

You can use JSON.parse to get the value(s) that you're looking for:
var myQuote = '{"success":true,"terms":"https:\/\/currencylayer.com\/terms","privacy":"https:\/\/currencylayer.com\/privacy","timestamp":1522395543,"source":"USD","quotes":{"USDGBP":0.71}}';
var jsonData = JSON.parse(myQuote);
document.getElementById("quote").innerHTML = jsonData.quotes.USDGBP;
<div id="quote"></div>

Try this :
var jsonObj = {
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1522395543,
"source":"USD",
"quotes":{
"USDGBP":0.71
}
};
document.getElementById('result').innerHTML = jsonObj.quotes.USDGBP;
<div id="result">
</div>

Related

Read text value and change the strings value?

I have the following code below. I want to change the H2 message No results were found for this query: <em class="querytext">to something like "No results were found by hello world! without hard coding as I have no control of the piece of text in an HTML file, is their any way I can do this via an if condition CSS or JS to read the string then change the message on load of the page? something like if text == No results were found for this query: display "No results were found by hello world!.
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em></h2>
</div>
You could try DOM manipulation with JavaScript:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script type="text/javascript">
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
</script>
<button onclick="updateResultText('hello world!')">Update Text</button>
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
</body>
</html>
The JS you need is below:
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
You would then make the call to updateResultText with whatever you want the text following 'by ' to consist of.
Here's a solution that uses vanilla JS to change all h2 that are child of .search-results class:
for (let h2 of document.querySelectorAll('.search-results > h2')) {
if (h2.textContent.search('No results were found for this query') >= 0)
h2.textContent = 'No results were found by hello world!';
}
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
old JavaScript
var query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
var newText = 'No results were found for this' + query ': <em class="querytext"></em></h2>'
var el = document.querySelector('.search-results h2').innerHTML = newText
ES5
const query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
const newText = `No results were found for this ${query}: <em class="querytext"></em></h2>`
const el = document.querySelector('.search-results h2').innerHTML = newText
At end of your page put the following script tag :
<script type="text/javascript">
var elem= document.querySelector('.search-results > h2');
if(elem) {
if(elem.innerText.indexOf("No results were found for this query")>=0)
elem.innerHtml="anything You want !!";
}
}
</script>
then after that there should be </body></html> tags.

can't select specific elements from data contained in <?!=JSON.stringify(dataFromServerTemplate) ?>

I have a problem with JSON format. I'm new at this kind of stuff so I can't figure out which is the problem. In google app script I have this get function
function doGet() {
var htmlTemplate = HtmlService.createTemplateFromFile('html');
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1_cj_HO2oN6CYe_Pb7Cy8S3yVtwKW8Efr-Sdyf1Sk8Ts/edit#gid=2009573145");
htmlTemplate.dataFromServerTemplate = makeJSON(getRowsData_(ss.getSheetByName("Foglio8"),getExportOptions()),getExportOptions());
var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('sample');
return htmlOutput;
}
Now, here is the part of the HTML which isn't working
<div>
<p id="tx"></p>
</div>
<script type="text/javascript">
var data = <?!=JSON.stringify(dataFromServerTemplate) ?>;
function caric(){
document.getElementById("tx").innerText= data.saldo;}
</script>
</body>
Function caric() runs onload of the page. "saldo" is actually contained in this JSON.
If I use data.saldoI receives undefined but if I only use data it works and prints everything that is contained in the JSON.
Do you know what I'm doing wrong?
Thanks
JSON.stringify produces a string not an object. In your server code you should do something like this.
var obj = { name: "me", gender: "male", eyes: "blue" };
htmlTemplate.dataFromServerTemplate = JSON.stringify(obj);
And on the client side this
var data = JSON.parse(<?= dataFromServerTemplate ?>);
(function caric(){
document.getElementById("tx").innerText= data.name;}());

Mustache.to_html() returning an empty string

This question was asked before but didn't get an answer. I have a php file which sends a json object to a javascript file which is supposed to render it with a template and display it on a div. The problem is, the function Mustache.to_html() returns empty. can anyone tell me what I am doing wrong. here's my code.
{
$(":button").click(function(){
var cat = $(this).attr("name");
$.get("trier.php",{input: cat}, function(data){
alert(data);
var template = $('#templabel').html();
console.log(template);
var html = Mustache.to_html(template, data);
console.log(html);
$('#feedback2').html(data);
});
});
}
The javascript sends the data to this php file which sends back a json object
{
if(isset($_GET['input'])){
$catt = $_GET['input'];
$info = "SELECT * FROM books WHERE (Category = '$catt')";
$information = mysqli_query($conn,$info);
$arraay = array();
while($r = mysqli_fetch_assoc($information)){
$arraay[] = $r;
}
$jason = json_encode($arraay);
$jason = '{"arraay":'.$jason."}";
echo $jason;
}
}
The javascript file will then send the json object rendered with the mustache template to the html file, to the tag with the id = "feedback2". But the display is raw json, not templated. and the second console.log after I apply the Mustache.to_html function returns an empty string. What am I doing wrong?
The output of the console.log for the template is
{{#arraay}}
<div>
<h2> {{Title}}</h2>
<p>{{Course}}</p>
<p>{{Category}}</p>
</div>
{{/arraay}}
and the alert for the data is
{"arraay":[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]}
Works for me:
var data = {"arraay":[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]};
var template = document.getElementById('template').innerHTML;
var html = Mustache.to_html(template, data);
document.getElementById('render').innerHTML = html;
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.0/mustache.min.js"></script>
<template id="template">
{{#arraay}}
<div>
<h2> {{Title}}</h2>
<p>{{Course}}</p>
<p>{{Category}}</p>
</div>
{{/arraay}}
</template>
<div id="render">
</div>

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

How to extract all hyperlink titles from big html string using javascript?

I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle

Categories