What is the best way to retrieve data from the previous webpage and navigate it to the appropriate page using HTML?

I have a pair of HTML files known as list.html and detail.html. From https://jsonplaceholder.typicode.com/posts, I am retrieving title and body data to exhibit on a posts.html page in the following format:

posts.html output

Displayed below is my posts.html code:

<!DOCTYPE html>
<html>
    <head>
        <title>List</title>
    </head>
    <body>
        <div id="post">
            <a>
                <h3 class="title"> </h3>
            </a>
            <p class="body"> </p>
        </div>
        <script src="fetch.js"></script>
    </body> 
</html>

Moreover, here is my JavaScript code snippet used within posts.html:

const api_url='https://jsonplaceholder.typicode.com/posts';

async function getISS(){
   const response = await fetch(api_url);
   const data= await response.json();
   let post = document.getElementById("post");
   
   for (let i = 1; i < data.length; i++) {
      const { id, title, body } = data[i]
      post.innerHTML += `<a href="detail.html">
      <h3 class="title">${title}</h3></a>
      <p class="body">${body} </p>`
   }
}  

getISS();

My objective is to navigate to the detail.html screen upon clicking a post's title, where only the selected post's title and body are displayed. For instance, by clicking the "qui est esse" title from the posts.html output image above, it should lead to detail.html showing only the title and body like this:

example output

If the second post "ea molestias quasi exercitationem repellat qui ipsa sit aut" title is clicked, it should again redirect to the detail.html screen but this time displaying only that specific title and body.

Below is my current detail.html code which does not contain anything significant yet:

<!DOCTYPE html>
<html>
    <head>
        <title>Detail</title>
    </head>
    <body>
        <h1>Title</h1>
        <p>Body</p>
        <script src="detail-script.js"></script>
    </body> 
</html>

I am fairly new to HTML and JavaScript development. I believe I need to utilize query strings for this functionality, however, I haven't been successful thus far. I am restricted to using solely native JavaScript without any frameworks. Can someone guide me on how I can achieve this?

Answer №1

Here is a simple solution to pass data from one HTML file to another using parameters in the URL. By adding a question mark followed by your parameter to the anchor tag's href attribute, you can send data between your posts.html and detail.html files. For example:

post.innerHTML += `<a href="detail.html?title=${title}">
  <h3 class="title">${title}</h3></a>
  <p class="body">${body} </p>`

If each title is unique, you can display only the specific title passed from posts.html in detail.html within your async function like this:

const urlString = window.location.href;
const url = new URL(urlString);
const titleString = url.searchParams.get("title")
for (let i=1;i<data.length;i++) {
   const { id, title, body } = data[i]
   if (titleString === title) {
       post.innerHTML += `<a href="detail.html?title=${title}">
       <h3 class="title">${title}</h3></a>
       <p class="body">${body} </p>`
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the width of the rail in Material UI's vertical Slider component in React

After attempting to adjust the width and height of the rail property on the material ui slider I obtained from their website demo, I have encountered an issue with changing the thickness. import React from "react"; import { withStyles, makeStyles } from " ...

Is there a way to set up a saving path using xhtml2pdf and provide a download link

I am currently using xhtml2pdf to convert my form into a PDF file. By default, it saves the PDF in the same location as my manage.py file. My question is how can I change the saving path to send the PDF to my Desktop, for example (running MacOSX). Below ...

"Encountering an unfamiliar authentication strategy while using NodeJS passport

I am currently developing a project using node.js with passport authentication. However, I am encountering the following error message: Error: "Unknown authentication strategy " Below is my code: LocalStrategy = require('passport-local').Strat ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

Parsing HTML using JavaCC

Recently, I've embarked on a journey with javacc and have been tasked with enhancing a basic html parsing using javacc code. My inquiry pertains to the <script> tags which contain numerous characters - like > and < that hold different mean ...

Can anyone recommend a super sleek drop-down navigation menu that includes both images and text descriptions?

My interest has been piqued on how to create a menu similar to the one on with all the images and text details. Does anyone have any insights on the technologies utilized for this? Are there any commercial options available that offer a similar functiona ...

A variety of negative () DOM Selectors

I've been trying to select a specific node using two not clauses, but so far I haven't had any luck. What I'm attempting to achieve is selecting an element whose div contains the string 0008, but it's not 10008 and also does not contain ...

Accessing the Next.js API after a hash symbol in the request URL

Is there a way to extract query strings from a GET request URL that contains the parameters after a '#' symbol (which is out of my control)? For example: http://...onnect/endpoint/#var_name=var_value... Even though request.url does not display a ...

Comparing Strict CSS with Hacky CSS - Which is the Better Choice?

When working with CSS, it becomes evident fairly quickly that certain styles are not universally compatible across different browsers. For instance, achieving a semi-transparent PNG required a convoluted solution for Internet Explorer like: filter: pro ...

What is the best way to transfer a string value from one class to another in order to utilize JSON?

I am currently facing an issue with passing a string value from one class to another. In my main class, I have two spinners and a date picker. The first spinner is for selecting the location and the second one is for choosing the stock point name. When a l ...

Tips for inserting JSON data into a MySQL database

function addToShoppingCart(id, quantity, type) { quantity = typeof(quantity) != 'undefined' ? quantity : 1; type = typeof(type) != 'undefined' ? type : 0; viewProduct = $("#viewProduct").val(); currentPage = $("#currentP ...

Getting text between Span tags using Selenium in Python

Struggling to extract the name "Margaret Osbon" from the following HTML using Python and Selenium. Despite trying different techniques, the printed output always comes out blank. <div class="author-info hidden-md"> By (autho ...

Dealing with POST redirection and retrieving parameters in Next.js

In a typical scenario, browsers send GET requests and servers return pages. However, in my case, I am making requests to a remote server and need to receive responses. The issue is that the server redirects me back to my page via a POST request with some d ...

Setting up JSP on a J2EE server using Eclipse

I'm encountering a specific issue with my setup. I am attempting to run JSP on a J2EE preview server within a Dynamic Web Project in Eclipse. While I know that it is possible to make it work by converting to a Maven project, adding dependencies, or us ...

Top IDE for web development with HTML5, JavaScript, CSS, and JQuery compatibility, alongside user-friendly GUI design capabilities

Currently, I am working on a project that involves using the RGraph HTML5 canvas package for graph drawing. In addition to this, I also need to create a visually appealing GUI. While experimenting with Netbeans, I found that it lacks the necessary featur ...

What is the proper HTML tag and syntax used for adding a text box within the content of a webpage?

Question about HTML: How can I add a text box or block to an HTML page that is filled with plain text? I want the text box to align to the right and be surrounded by the plain text, essentially wrapping around it. I also need to specify the dimensions of ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

We were unable to locate the requested resource

I have been working on setting up an Express endpoint to fetch comments or reviews of a movie based on the movie ID. In my initial route, I manually passed the ID and retrieved data from TheMovieDB. However, I wanted to make this process dynamic in my seco ...

What is the best way to create a footer in this scenario and is there a method to perfectly center an

What is the best way to position the footer at the bottom of the page without overlapping the top content? Is there a method to center both the height and width of the header element on the page? Can you review the layout of this webpage and provide feed ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...