Js classname doesn't work with fetch json - javascript

how is going?
So I've made this API code here:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// API Endpoint
var x = document.getElementsByClassName("name1");
var y = document.getElementsByClassName("name2");
var i;
var url = 'mysite.org/api.php'
// Fetch the remote file
fetch(url)
.then(function (request) {
// Take the request and parse the data as json
return request.json()
})
.then(function (json) {
// line1
var name1 = json.item1.name // current song title
x.innerHTML = name;
// line2
var name2 = json.item2.name // current song title
y.innerHTML = name2;
});
});
</script>
</head>
<body>
<h5>Hello</h5>
<div class="name1"></div>
<div class="name2"></div>
</body>
</html>
api.php ((the json is generated by array from a cicle while))
{"item1":{"id":"1","name":"Daniel"},"item2":{"id":"2","name":"Kalifa"}}
So this code works fine and I can see item1 inside div id name1 and item2 inside div id name2. But I dunno why but when I try to change the elements from ID to CLASS it doesn't work.
Any ideas?

Loop over the object keys in the JSON, get the element with the same class, and assign its innerHTML.
Object.entries(json).forEach(([name, value]) =>
document.getElementsByClassName(name)[0].innerHTML = value);
When you use getElementsByClassName() you need to index it to get the first element with that class.

Related

Issue with API url: cannot seem to pass parameters correctly

I'm new at APIs and am trying for the first time to create a gallery using Flickr API, but I'm really struggling getting it to work properly.
I have created the url correctly, and if I insert the search parameters directly in the url, when I console log I can see the correct list of images. The issue occurs when I'm trying to pass parameters from variables into the url. And the error manifests in two different ways, depending whether I put the url variable before or after the parameters variables.
Case 1:
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
In this case it will console log data, but using parameters of its choice.
Case 2:
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
In this case it will return the following error message: {stat: "fail", code: 3, message: "Parameterless searches have been disabled. Please use flickr.photos.getRecent instead."}
I seem to not be passing parameters to the url correctly, cause I'm also having an issue when trying to create the gallery itself, where when I'm trying to pass the necessary ids from the images in the API array to the image url I'm creating, these parameters end up being undefined.
This is the code I've written:
function createGallery(photos) {
for (let photo of Object.keys(photos)) {
const imgElem = document.createElement('li');
imgElem.innerHTML = `<img src='https://farm{${photo.farm}}.staticflickr.com/{${photo.server}}/{${photo.id}}_{${photo.secret}}_[mstzb].jpg'></img>`;
imgElem.setAttribute('img-id', photo.id);
gallery.append(imgElem);
}
}
Just for an overview, here is the last bit of my JS:
//Fetch API
async function start() {
const response = await fetch (url)
const data = await response.json()
console.log(data)
createGallery(data)
}
//Call functions
search()
And here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<input type="text" id="input">
<button id="search">Go</button>
<ul id="gallery"></ul>
</main>
<script src="script.js"></script>
</body>
</html>
Anyone can explain what I'm doing wrong?? Thanks so much in advance :)
EDIT: I tried appending the variables using pluses instead of using template literals, like so:
var url = 'https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text='+searchWord+'&per_page='+perPage+'&page='+page+'&format=json&nojsoncallback=1';
But both ways give exactly the same result.
You are basically appending the parameters incorrectly.
You have the following:
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
When you define that url it should be similar to this ..
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=' + searchWord + '&per_page=' + perPage + '&page=' + page + '&format=json&nojsoncallback=1'
Please note the difference there, we are actually just building up the url var by appending the JS variables to the String. There is no ${} access to the declared page and perPage JS vars...

Function parameter is not being passed. How to correctly pass parameter into function of another JavaScript file?

I want to to call a function file2Function(getValue) of a file (page2.js) from another JavaScript File (page1.js) to open new page in browser and display some data on it using parameter passed viamyFunction1(e) into file2Function as file2Function(itemFromItems). So file2Function(getValue)should take value of var itemFromItems and should display on page2.html. But it is displaying "undefined" for getValue. Kindly help me finding out where I am doing Mistake. Thank You.
// page1.js
function file1Function()
{
var secPage1 = document.getElementById("page1Section");
var heading = document.createElement("h4");
var anchor= document.createElement('a');
anchor.setAttribute('href',"#");
anchor.innerText = "Click Me";
anchor.addEventListener("click", myFunction1);
heading.appendChild(anchor);
secPage1.appendChild(heading);
anchor.id=1;
function myFunction1(e) {
var itemFromItems = e.currentTarget.getAttribute("id");
console.log("item",itemFromItems);
file2Function(itemFromItems);
}
}
// page2.js
var globalVar;
function file2Function(getValue)
{
console.log("getValue",getValue);
window.open("page2.html");
// window.open("https://www.google.com/");
globalVar=getValue;
console.log("globalVarNow",globalVar);
}
function loadDynamicData()
{
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
<!-- page1.html -->
<!DOCTYPE html>
<html>
<head>
<script src="js/page1.js"></script>
<script src="js/page2.js"></script>
</head>
<body onload="file1Function()">
<h3>This is page1</h3>
<section id="page1Section">
</section>
<script>
</script>
</body>
</html>
<!-- page2.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="loadDynamicData()">
<h3>This is page2</h3>
<section id="page2Section">
</section>
<p id="paraId"></p>
<script src="js/page2.js"></script>
</body>
</html>
The problem is that globalVar is a global variable, but the value you are assigning to it in file2Function() is accessable only within its scope, that is why you are getting undefined, because loadDynamicData() has no access to the new value of globalVar.
You could call loadDynamicData() from file2Function() and pass getValue as an argument, but since you need to open page2 before executing loadDynamicData() it won't work.
What I suggest is you pass getValue along with your URL as a query parameter and get it from inside loadDynamicData(), it'll work fine.
SOLUTION:
function file2Function(getValue)
{
window.open("page2.html?value="+getValue);
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var url_string = window.location.href
var url = new URL(url_string);
var globalVar = url.searchParams.get("value");
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
If you want to hide the values you can use sessionStorage instead of query parameters:
function file2Function(getValue)
{
sessionStorage.setItem('value', getValue)
window.open("page2.html");
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var globalVar = sessionStorage.getItem('value')
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}

How to get a value of a counter within a script tag

I would like to retrieve the value of a counter made by a
script I've not access to, to show it on another webpage.
The remote webpage looks like this :
<!doctype html>
<html lang="fr-FR">
<head>
<script>
window.changeTargetingData = {"Count":{"total":123456}, "Week":12345};
</script>
</head>
</html>
Is it possible to get the "total" value since it is inside a script tag ? And to refresh this value, say, every hour ?
Thanks
Every time you want to check the value, you can make a request to the webpage, parse it into a document, then select the <script> tag and examine its textContent:
const textResponse = `<!doctype html>
<html lang="fr-FR">
<head>
<script>
window.changeTargetingData = {"Count":{"total":123456}, "Week":12345};
<\/script>
</head>
</html>`;
/*
fetch(url)
.then(res => res.text())
.then((textResponse) => {
*/
const doc = new DOMParser().parseFromString(textResponse, 'text/html');
const script = doc.querySelector('script');
const objJSON = script.textContent.match(/window.changeTargetingData = (.+);/)[1];
const obj = JSON.parse(objJSON);
console.log(obj.Count);
If you can't make a request directly to the site, and you're on the front-end, you'll have to bounce the request off a server which can relay it without CORS restrictions.

Can I get an object from jquery document

Can I do the following
lets assume I get page content like
var data = $('html').html();
if the page contain object
mydata = {
test:"mydata"
}
can I access this object some how ?? I want to get the info stored in that object like
console.log(data.mydata);
and it should return
test:"mydata"
Is there are way to get an object from JQuery data object like
var data = $('html').html();
note: the object in script tag like this
<script>
window.mydata = {
test:"mydata"
}
</script>
as I said I'm trying to access the data through jquery object or returned dom
var data = $('html').html();
I don't have direct access to window.mydata
is there anyway to access window.mydata from the data returned from this function
$('html').html();
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<h1>Hello World</h1>
<p>Lorem Ipsum</p>
<script type="text/javascript">
var data = $('html').html();
var mydata = {
test:"mydata"
}
console.log(data);
console.log(mydata); // Object { test: "mydata" }
console.log(mydata.test); // "mydata"
</script>
</body>
</html>
You can attach data in a DOM element using the .data API and retrieve it in the same format.
In your case it will be something like
<script>
window.mydata = {
test:"mydata"
}
$("html").data("someKey", window.myData);
// later retrieve it
var data = $("html").data("someKey");
console.log(data.test); /* should print mydata */
</script>
Update (after OP comment)
// assign your string which you get from Amazon to this variable
var fileContents = 'Some text which has script tags <script>window.mydata = {test:"mydata"}<\/script>';
$("#codeInject").html(fileContents).hide();
console.log(window.mydata);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="codeInject"></div>

Using Google Images API

I'm trying to use Google's Images API to search an image and put it into my html document as a div. This is what I have so far, but nothing seems to be appearing. This is parts from http://code.google.com/apis/imagesearch/v1/devguide.html. This is my first time using an API, so I'm not sure what is really going on.
<html>
<head>
<title>Art Project FTW</title>
</head>
<body>
<br>
<br>
<form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
</form>
<script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
<script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('h2');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
}
}
function onload() {
// Our ImageSearch instance.
var imageSearch = new google.search.ImageSearch();
// Restrict to extra large images only
imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
google.search.ImageSearch.IMAGESIZE_MEDIUM);
// Here we set a callback so that anytime a search is executed, it will call
// the searchComplete function and pass it our ImageSearch searcher.
// When a search completes, our ImageSearch object is automatically
// populated with the results.
imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);​
</script>
</body>
</html>
Thanks in advance!
It can't work because you are looking for a HTMLElement that has the ID='content', you haven´t anyone element with that ID
Try putting your js functions within <head></head>

Categories