0

When i do a document.location.href to go to another HTML page and then try to modify elements in the new page (which I would use getElementById for), I get that the element is not found in the webpage. I think it is because the new page is not fully loaded yet and it is looking in the previous HTML page.. Any idea how I can fix this issue? For example:

async function navigateToAccount(accId, userStatus, userBalance) {
  //fetch account information
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(
      'someapi/api/getAccountDetails/' + accId,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      }
    )
    const data = await response.json()
    if (data.status == false) {
      throw new Error(data.message)
    }
    window.location.href = 'accountPage.html'
//the below is not executing
    const accountName = document.getElementById('accountPageName')
    accountName.textContent = localStorage.getItem('name')
    const accountBalance = document.getElementById('accountPageBalance')
    accountBalance.textContent = userBalance
    const ccNumber = document.getElementById('accountPageccNumber')
    ccNumber.textContent = data.account.creditCard.number
    const ccName = document.getElementById('accountPageccName')
    ccName.textContent = localStorage.getItem('name')
    const ccExp = document.getElementById('accountPageccExp')
    ccExp.textContent = data.account.creditCard.expiryDate
    const ccCvv = document.getElementById('accountPagecccvv')
    ccCvv.textContent = data.account.creditCard.cvv
  } catch (err) {
    console.log(err.message)
  }
}

I would get an error saying that element with Id accountPageName is not found.

akvn
  • 57
  • 1
  • 8
  • 3
    I don't really understand. If you redirect the user to another HTML file, then the current process ends. After that, you need to encode what you want in the new file. – rozsazoltan Jun 18 '23 at 14:24
  • @rozsazoltan why is it not finding the element that is in the new page then? – akvn Jun 18 '23 at 14:27
  • because `'accountPage.html'` is a bad value. you may use `window.location.pathname = "accountPage.html";` – Mister Jojo Jun 18 '23 at 14:31
  • @MisterJojo Nothing changes when I use that. I also tried window.location.replace.. Same issue. Note that it redirects me to accountPage.html.. but the DOM manipulation I am doing after it redirects me are not happening. – akvn Jun 18 '23 at 14:33
  • 1
    [there may be a thousand other reasons, you are bound to make a mistake somewhere, but it is impossible to determine which one with the little information you have provided here](https://stackoverflow.com/questions/how-to-ask) – Mister Jojo Jun 18 '23 at 14:38
  • View the new page's source. Do you see your script? From what you've written, no. You can't use the script from one page on another unless you explicitly include it. – Andy Jun 18 '23 at 14:40
  • @Andy Yes I do see it and as I said it is redirecting me to the new page as I want but everything after (setting text to elements in the new page) is not executing because it cannot find element with id accountPageName although it is in the new page. – akvn Jun 18 '23 at 14:43
  • 1
    As mentioned before: After the redirection, the new webpage is not loaded within your current page, but the JavaScript redirects to the new webpage. **It's like manually typing the URL address `http://example.com/accountPage.html` into the browser's address bar. The two pages have no connection to each other, and their elements cannot access each other.** – rozsazoltan Jun 18 '23 at 14:44
  • **If you want to pass data from one page to another, you need to include them in the redirection**, for example, using the GET method: `http://example.com/accountPage.html?variableName=variableValue&anotherVariableName=anotherVariableValue`. In this case, you can extract the variables and their values from the URL, which can be utilized in the new page. – rozsazoltan Jun 18 '23 at 14:44
  • 1
    @rozsazoltan I have updated my question with my full code. What I am doing is basically whenever a button is pressed on a page, the function navigateToAccount is called that fetches the account details and displays them in the new page accountPage.html – akvn Jun 18 '23 at 14:47
  • 1
    You don’t seem to get it. What happens is 1. You redirect the user to another page. 2. A new page is loaded. – Klaassiek Jun 18 '23 at 15:12
  • 2
    As soon as you redirect the user, the browser will load the new page. Any code after the redirection will never get executed. As mentioned before in the comments: if you want javascript to get executed on the new page, you have to include that in the new page. The old page doesn’t exist anymore, so any of the old page’s javascript doesn’t work on the new page. – Klaassiek Jun 18 '23 at 15:14
  • @rozsazoltan Thank you for your answer. Regarding the code that will run when loaded accountPage.html . I have to put it inside `document.addEventListener('DOMContentLoaded', function () {` . Correct? – akvn Jun 18 '23 at 15:19
  • Using `document.addEventListener('DOMContentLoaded', function () {...}`) is justified when you want to ensure that the code runs only when the `accountPage.html` has fully loaded, and all DOM elements have become accessible. (In the current scenario, it can be considered for use. You don't need to include the entire functionality, just the invocation of retrieving user data. To [my answer](https://stackoverflow.com/a/76501185/15167500) --> ``document.addEventListener('DOMContentLoaded', function () { getAccountDetails(params.accId) }``) – rozsazoltan Jun 18 '23 at 15:22

1 Answers1

0

You can do two things.

First, you request the data from the current page, then you invoke the new page and pass it the data. This is what you would have done with your code, but incorrectly. I think this is cumbersome and unnecessary. (bad)

Second, you open the new page, pass the user ID to it if necessary - although I think it can be queried - and that's all we need to do on the current page because we redirected the user to a new file. On the new page, you then download the user data. (better)

(I would choose this approach for another reason as well. Just imagine if you want to redirect the user to the accountPage.html from another file. Then, would you have to encode the data retrieval again there? That would be code duplication and quite a cumbersome task. Instead, you should encode everything that belongs to it directly into the accountPage.html. If downloading the account data is necessary for the proper display of the page, then you should perform that data retrieval within the accountPage.html.)

home.html

<button onclick="navigateToAccount(123)">Go to My Account</button>
/**
 ** Will run when loaded home.html and click to button
 */
function navigateToAccount(accId) {
  window.location.href = `../accountPage.html?accId=${accId}` // redirect to new html file and here end current request
}

accountPage.html

<div id="accName">Loading...</div>
/**
 ** Will run when loaded accountPage.html
 */

// Get Params from URL (http://example.com/accountPage.html?accId=123)
// - after it can call params.accId what is return 123
const params = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop),
})

let accountDetails = null

async function getAccountDetails(accId) {
  const response = await fetch(`http://example.com/api/getAccountDetails/${accId}`) // wait API response 
  accountDetails = await response.json() // save API answer

  // call print method
  printAccountDetails()
}

// print texts to divs
function printAccountDetails() {
  document.getElementById('accName').innerText = accountDetails?.accName ?? 'unknown'
}

// Call get method after DOM loaded fully
window.addEventListener("DOMContentLoaded", (event) => {
  getAccountDetails(params.accId)
})

More information

Jumping to a new HTML page with JavaScript - StackOverflow Answer
How can I get query string values in JavaScript - StackOverflow Answer
Using the Fetch API in JavaScript - MDN Docs

await - Wait process end - MDN Docs
async function - What need to await using - MDN Docs

DOMContentLoaded event - MDN Docs

rozsazoltan
  • 2,831
  • 2
  • 7
  • 20
  • [Clone] Using `document.addEventListener('DOMContentLoaded', function () {...}`) is justified when you want to ensure that the code runs only when the `accountPage.html` has fully loaded, and all DOM elements have become accessible. (In the current scenario, it can be considered for use. You don't need to include the entire functionality, just the invocation of retrieving user data. To [my answer](https://stackoverflow.com/a/76501185/15167500) --> ``document.addEventListener('DOMContentLoaded', function () { getAccountDetails(params.accId) }``) – rozsazoltan Jun 18 '23 at 15:26