Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Javascript API trouble

Kobraz

New Coder
Hi.

Anyone who can help me with this problem - (Im studying Front-End Dev)?

I have an API from WordPress:
https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/posts/ and from this I can access my text ( under description.rendered). But I need to go to this URL
https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/media/ to get the images, titles etc.

I keep getting errors...

1684968439195.png
My files:

HTML:

<!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"> <title>Document</title> <script src="js/loading.js"></script> <link rel="stylesheet" href="css/loading.css"> </head> <body> <main> <h1 id="tittel" class="tittel">Tittel</h1> <div class="loading"></div> <div class="container"> <div id="titleContainer"> </div> <div id="dateContainer"> </div> <div id="imageContainer"> </div> <div id="textContainer"> </div> </div> </main> <script src="js/details.js" defer></script> </body> </html>


JAVASCRIPT:

const query = document.location.search; const params = new URLSearchParams(query); const id = params.get("id"); const post = id; const apiBase = "https://falchhanssen.net"; const blogBase = "/student/ProjectExam1/blog"; const postBase = "/wp-json/wp/v2/posts"; const mediaBase = "/wp-json/wp/v2/media"; // const fullPostURL = apiBase + blogBase + postBase + id; // const fullMediaURL = apiBase + blogBase + mediaBase + post; const fullPostURL = 'https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/posts/' + id; const fullMediaURL = 'https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/media/' + id; async function getDetail() { const responsePost = await fetch(fullPostURL); const dataPost = await responsePost.json(); console.log('dataPost: ', dataPost); const responseMedia = await fetch(fullMediaURL); const dataMedia = await responseMedia.json(); console.log('dataMedia: ', dataMedia); const titleContainer = document.getElementById("titleContainer"); const dateContainer = document.getElementById("dateContainer"); const imageContainer = document.getElementById("imageContainer"); const textContainer = document.getElementById("textContainer"); titleContainer.innerHTML += `<div>${dataMedia.title}</div>`; dateContainer.innerHTML += `<div>${dataMedia.date}</div>`; imageContainer.innerHTML += `<div>${dataMedia.medium}</div>`; textContainer.innerHTML += `<div>${dataPost.description}</div>`; console.log('title: ', dataMedia.title); try { console.log(dataMedia.title); } catch (err) { alert(err); } } getDetail();
 
Can you please post your code using the </> button instead of the >_ button ? I now realize I've been mistakenly advising people to use the latter 😳
That last error is one I am getting almost all the time. Never worked out what the issue is but I've never found it to be a problem. Just ignore it.
Your real error is that dataMedia.title is not defined. Being not too familiar with fetch and json I am not sure what's wrong. Why not add these statements

JavaScript:
console.log(responseMedia);
console.log(dataMedia);

and inspect both objects in the Console, see what type they are and which members they have.
 
Not sure I understand right what OP wants to achieve, but hope this might be useful:

HTML:
<!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">
<title>Document</title>
<style>
[class*=Links] a{
text-decoration: none;
margin-left: 5px;
color: blue;
font-weight: bold;
}

[class*=Links] a:hover{
color: crimson;
}
</style>
</head>
<body>
<main>
<h1 id="tittel" class="tittel">Tittel</h1>
<div class="loading"></div>
<div class="postLinks">Post links:</div>
<!--div class="mediaLinks">Media links:</div-->
<div class="container">
<div id="titleContainer"></div>
<div id="dateContainer"></div>
<div id="imageContainer"></div>
<div id="textContainer"></div>
</div>
</main>
<script>
function _(attr){
    return !arguments[1] ? document.querySelector(attr) : document.querySelectorAll(attr);
}

const fullPostURL = 'https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/posts/',
      fullMediaURL = 'https://falchhanssen.net/student/ProjectExam1/blog/wp-json/wp/v2/media/';

let postObject = null,
    mediaObject = null,
    postIDs = [],
    mediaIDs = [];

(async function(){

const responsePost = await fetch(fullPostURL),
      postObject = JSON.parse(JSON.stringify(await responsePost.json())),
      responseMedia = await fetch(fullMediaURL),
      mediaObject = JSON.parse(JSON.stringify(await responseMedia.json()));

postIDs = postObject.map( x => x.id ); // [28, 26, 24, 19, 17, 14, 12, 6, 8]
mediaIDs = mediaObject.map( x => x.id ); // [76, 74, 72, 70, 68, 66, 64, 62, 60]
/*
console.log( postIDs );
console.log( mediaIDs );
*/
_('.postLinks').insertAdjacentHTML('beforeend', postIDs.sort( (a, b) => a - b ).map( a => `<a href="#null">${a}</a>` ).join(''));

_('.postLinks').addEventListener('click', (e) => {
const trg = e.target;
if(trg.tagName != 'A') return;
const oP = postObject.filter( n => n.id == trg.textContent )[0],
      oM = mediaObject.filter( m => m.id == oP.featured_media )[0];

_('#titleContainer').innerHTML = oP.title.rendered;
_('#dateContainer').innerHTML = oP.date;
_('#imageContainer').innerHTML = `<img src="${oM.guid.rendered}">`;
_('#textContainer').innerHTML = oM.description.rendered;
});

/*
_('.mediaLinks').insertAdjacentHTML('beforeend', mediaIDs.sort( (a, b) => a - b ).map( a => `<a href="#null">${a}</a>` ).join(''));
do something
*/

})();
</script>
</body>
</html>

P.S. beatiful pictures, fantastic sights
 
Great code @Padonak ! The OP gets their complete solution presented on a tray, and I get to learn some new tricks 😀

For my benefit, could you clarify two things ?

CSS:
<style>
[class*=Links] a{
What's up with this [class=*Links] ?

JavaScript:
(async function()
{
    const responsePost = await fetch(fullPostURL),
    ...
});
Why is this between parentheses ? Is this like an anonymous code block which is always executed ?

Thanks!
 
Hi there, cbreemer ) [attribute *= str] selects every element having str at any position.

  • [attr] – attr defined,
  • [attr="val"] – attr equals to val,
  • [attr^="val"] – attr starts with val, for example "value",
  • [attr|="val"] – attr equals to val OR starts with val,
  • [attr*="val"] – attr contains substring val, for example "myvalue",
  • [attr$="val"] – attr ends with val, for example "myval",
  • [attr~="val"] – attr contains val one of values joined with " " (space)
For example, [attr~="delete"] is true for "edit delete" but false for "undelete" and "no-delete".

( function(){some code} )(); is self-executed

By the way, I've just noticed that my code posted above needs changing this fragment

JavaScript:
const responsePost = await fetch(fullPostURL),
      postObject = JSON.parse(JSON.stringify(await responsePost.json())),
responseMedia = await fetch(fullMediaURL),
mediaObject = JSON.parse(JSON.stringify(await responseMedia.json()));

postIDs = postObject.map( x => x.id ); // [28, 26, 24, 19, 17, 14, 12, 6, 8]
mediaIDs = mediaObject.map( x => x.id ); // [76, 74, 72, 70, 68, 66, 64, 62, 60]

to this one

JavaScript:
const responsePost = await fetch(fullPostURL),
      responseMedia = await fetch(fullMediaURL);


postObject = JSON.parse(JSON.stringify(await responsePost.json()));
mediaObject = JSON.parse(JSON.stringify(await responseMedia.json()));
postIDs = postObject.map( x => x.id ); // [28, 26, 24, 19, 17, 14, 12, 6, 8]
mediaIDs = mediaObject.map( x => x.id ); // [76, 74, 72, 70, 68, 66, 64, 62, 60]
 
Last edited:
Thanks for the explanation @Padonak ! Useful features especially the self-executing function. I'm not sure I'll want to use that CSS trick. Always hated regex 😀
Not fully grasping your change though. Is this necessary because the execution order of that compound const statement is not guaranteed ?
 
I'm not sure I'll want to use that CSS trick
Those selectors can be very useful when you need to select a certain collection from DOM. document.querySelectorAll('[class*=Links] a') selects all the anchors within these two divs:

HTML:
<div class="postLinks">Post links:</div>
<div class="mediaLinks">Media links:</div>

Is this necessary because the execution order of that compound const statement is not guaranteed ?

No, that was the matter of scope.

JavaScript:
let postObject = null,
    mediaObject = null,

These two objects are declared "empty", but then they are "filled" by that self-exec function. Once these objects filled, we don't need to fetch again and again every "post" or "media" object adding its id to url like OP did in his code. We already have everything in these objects. So, we can filter these objects to extract what we nedd from them. Sorry for bad english and "non-programmer's" explanations, you know i'm just a plumber 🛠️:D
 
Thanks for your explanations, very useful. I missed the fact you were declaring postObject and mediaObject twice. The new code is better for sure.
"Just a plumber" 😅 Haha, you kid me not 😎
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom