1

In php I wrote this:

<?php include "file.php" ?>

Inside html file, I wrote this:

<script src='file.js'></script>

Now, I'm working with a js file.

Inside this js file, I want to include html file like this.

<script>
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
</script>

Thanks a lot.

2
  • 1
    Try this between the script tags `var phpFile = <?php include "file.php" ?> ? Commented Feb 9, 2019 at 15:13
  • its inside external js file Commented Feb 9, 2019 at 15:14

1 Answer 1

2

You can't call HTML file inside an external JS file, but you can create a helper function for that.

Following this tutorial you will be able to get something like this:

function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = "filename.html";
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}

          //elmnt.innerHTML - THIS HTML FROM YOUR FILE
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
Sign up to request clarification or add additional context in comments.

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.