how to get image from webpage which is a javascript object - javascript

i am making a meme api webpage
i want the webpage to display a new meme fetched from reddit using reddit api.
i have completed the api and it perfectly shows new memes on every refresh.
i want to embed these images in readme markdown as images
for that i am using
<img src="https://mywebpage.com/">
but i am not getting images when embedded in md.
Here is the code of my webpage-
index.html-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="script.js"></script>
</head>
<body>
<img src="loading.gif" id="meme" alt="meme didnt load :(" width="256px">
</body>
</html>
Script.js-
// function to fetch memes
function meme () {
let fetchRes = fetch("https://www.reddit.com/r/ProgrammerHumor/hot.json");
fetchRes.then(res => res.json()).then(d => {
// Generates a random number for the random meme
var randomNumber = Math.floor(Math.random() * 26)
// Actually gets the data from the api
var memeImg = d.data.children[randomNumber].data.url
var permalink = d.data.children[randomNumber].data.permalink
var postURL = `https://reddit.com${permalink}`
// setting the text to the data
document.getElementById('meme').src = memeImg;
})
}
// Reload page button
function reloadPage () {
document.location.reload(true)
}
// Calling the meme function
meme()

Related

Loading in an Image Ranomizer API within javascript to display on an HTML

I'm very new to programming.
I'm working on a school project, and I was given an API that displays random dogs each time the web browser is refreshed. For whatever reason I'm getting a 404 error, but I can see the url changing along with the dog breed within the console. On my HTML page I get the broken image icon where the photo is suppose to load in.
Here is my code:
let xhrdog = new XMLHttpRequest(); //first ajax request, dog photos from api
xhrdog.onreadystatechange = function() {
if (xhrdog.readyState === 4) {
if (xhrdog.status === 200) {
let ajdog = JSON.parse(xhrdog.responseText);
let image = document.createElement('img')
image.src = ajdog //xhrdog.responseText;
let dog = document.getElementById('dog')
dog.appendChild(image);
}
}
}
xhrdog.open('GET', 'https://dog.ceo/api/breeds/image/random');
xhrdog.send();
Any help would be greatly appreciated.
You are very nearly there. It is just that, as you had spotted in the console, you are getting more than the img url back from the service. It is sending a string which you can parse as JSON, as you are doing.
When you have parsed it you actually have an object, not just a single string, in ajdog. One item in that is 'message' and that holds the full url of the dog image. So use ajdog.message rather than just ajdog to put in your img.src.
Here's the snippet with this change:
let xhrdog = new XMLHttpRequest(); //first ajax request, dog photos from api
xhrdog.onreadystatechange = function () {
if (xhrdog.readyState === 4) {
if (xhrdog.status === 200) {
let ajdog = JSON.parse(xhrdog.responseText);
console.log(xhrdog.responseText);//LOOK IN THE CONSOLE TO SEE WHAT IS SENT
let image = document.createElement('img');
image.src = ajdog.message; //xhrdog.responseText;
let dog = document.getElementById('dog');
dog.appendChild(image);
}
}
}
xhrdog.open('GET', 'https://dog.ceo/api/breeds/image/random');
xhrdog.send();
<div id="dog"></div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="" alt="">
<script>
//https://dog.ceo/api/breeds/image/random
async function randomDog(){
//store the promise with url
const result = await fetch('https://dog.ceo/api/breeds/image/random').then((data)=>{
return data.json()
})
//return a object
return result
}
//instanstiate image
const img= document.querySelector('img')
//this function is returning a promise
randomDog().then((data)=>{
//console.log(data)
img.setAttribute('src',data.message)
})
</script>
</body>
</html>

Trying to use EXIF.js to return GPS coords when a jpg image is clicked

I'm trying to add javascript functionality that will return gps coordinates from exif data when the user clicks on a jpg displayed on the page. (Will use that to open a google map). I have managed to produce a working example when the script is inline in the html file, but not when trying to use a separate script file, getCoords.js
Found a similar question here: How to pass images from server to function in JavaScript?
What I'm trying to do is pass the src attribute from the html click event into the script. The script is getting the src, I can print that to the console and launch the jpg in devtools by clicking on the link in the console. But it doesn't seem to be even trying to run
EXIF.getData(my_image, function() {...
Here's the HTML:
<html lang="en">
<head>
<title>Map Test Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="styles.css" rel="stylesheet">
<script src="getCoords.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js">
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMLVQ6kCIfX4c8vVHa0qOf8P87DxCvt2w">
</script>
</head>
<body>
<picture>
<source media="(min-width: 750px)" srcset="images/van_from_erp2_L.jpg 2x, images/van_from_erp2_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/van_from_erp2_m.jpg" />
<img src="images/van_from_erp2_s.jpg" id="hiking_0" alt="View of Vancouver from ridge" onclick='getCoords(src)'>
</picture>
<picture>
<source media="(min-width: 750px)" srcset="images/creek_1_l.jpg 2x, images/creek_1_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/creek_1_m.jpg" />
<img src="images/creek_1_s.jpg" id="hiking_1" alt="forest creek image" onclick='Hello(id)'>
</picture>
<!--div id="map"></div-->
</body>
</html>
and here's the script:
function getCoords(source) {
console.log(source);
//pass image to EXIF.js to return EXIF data (EXIF.js sourced from github)
let my_image = new Image();
my_image.src = source;
console.log("hello from line 7");
EXIF.getData(my_image, function() {
console.log("Hello from line 9");
myData = this;
console.log(myData.exifdata);
// get latitude from exif data and calculate latitude decimal
var latDegree = myData.exifdata.GPSLatitude[0].numerator;
var latMinute = myData.exifdata.GPSLatitude[1].numerator;
var latSecond = myData.exifdata.GPSLatitude[2].numerator;
var latDirection = myData.exifdata.GPSLatitudeRef;
var latFinal = ConvertDMSToDD(latDegree, latMinute, latSecond, latDirection);
//console.log(latFinal);
// get longitude from exif data and calculate longitude decimal
var lonDegree = myData.exifdata.GPSLongitude[0].numerator;
var lonMinute = myData.exifdata.GPSLongitude[1].numerator;
var lonSecond = myData.exifdata.GPSLongitude[2].numerator;
var lonDirection = myData.exifdata.GPSLongitudeRef;
var lonFinal = ConvertDMSToDD(lonDegree, lonMinute, lonSecond, lonDirection);
//console.log(lonFinal);
let site = [latFinal, lonFinal];
console.log(site);
return(site);
// Create Google Maps link for the location
//document.getElementById('map-link').innerHTML = 'Google Maps';
});
//};
function ConvertDMSToDD(degrees, minutes, seconds, direction) {
var dd = degrees + (minutes/60) + (seconds/360000);
if (direction == "S" || direction == "W") {
dd = dd * -1;
}
return dd;
}
}
Put EXIF.getData(my_image, function() {...} inside the image onload function:
my_image.onload = function() {
EXIF.getData(my_image, function() {...}
}
Note that you have to wait for the image to be completely loaded,
before calling getData or any other function. It will silently fail
otherwise. Docs

How to update html document using feather js?

I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>

Real time data extraction JSON

I have written a code which extracts a specific table from a webpage. The website is dynamic and it updates the values in the table once every half an hour. My Javascript for parsing the website does reload the website once every 30 minutes. But the data extracted as JSON are only data of the particular time. But, I want to append or concatenate all the data every time the site reloads(i.e., i need the present list of data concatenated with previous list, as long as the program is running) How do i do that?.
The webpage is: https://www.emcsg.com/marketdata/priceinformation
The table required is: View 72 periods
My code is as follows:
<html>
<head>
<title>Pricing </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<meta http-equiv="refresh" content="1800" /><!--Reloads page every 30 minutes-->
<script>
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
function someFunction(results){
var html = $(results);
var table = html.find(".view72PeriodsWrapper");
$('#loadedContent').css("display","").html(table);
}
</script>
</head>
<body>
<br><br>
<div id="result"></div>
<div id="loadedContent"></div>
</body>
</html>

Simple youtube javascript api 3 request not works

i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply

Categories

Resources