1

I have a collection of buttons and when I click them I am trying to display the HTML from a different file. I tried dabbling in JQuery but I decided I want to try doing it with fetch

4
  • Did you get content of file in front-end Commented Dec 4, 2019 at 4:13
  • from where are you reading the content of html file Commented Dec 4, 2019 at 4:16
  • check if you get content in response. Commented Dec 4, 2019 at 4:19
  • maybe try: fetch('content.php').then(res => res.text()).then(response => content.innerHTML = response); Commented Dec 4, 2019 at 4:21

2 Answers 2

3

If you're using jquery, you can try to use .load() method:

$(content).load('content.php');

Or if you still want to use fetch method:

fetch('content.php')
    .then(function(response) {
        var html = response.text();

        var parser = new DOMParser();

        var doc = parser.parseFromString(html, "text/html");

        content.innerHTML = doc.innerHTML;
    });
Sign up to request clarification or add additional context in comments.

2 Comments

The question is tagged and asked as javascript.
@Marissa Updated!
0

This is the right way to do it using fetch().

fetch('content.php').then(res => {
  if (response.status !== 200) {
    console.log(`Looks like there was a problem. Status Code: ${response.status}`);
    return
  }

  res.text().then(text => {
    content.innerHTML = text
  })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.