Insert HTML code in Client-side form without using PHP

Asked

Viewed 59 times

0

Guys I have two external files called header.html and footer html containing headers and footer of a site, with menus and etc. I need to include these external files in the site pages without using PHP.

There’s a way to do something like:

<?php require_once("include/header.html"); ?>

Making use of javascript or otherwise that is Client-side and not Server-side as in other answers?

2 answers

1


Create a div on each location you want to upload the files with ids header and footer and pull them via Ajax:

var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    http = new XMLHttpRequest();
}

var paginas = ["header","footer"];

window.onload = function(){
    carrega_paginas(0);
}

function carrega_paginas(i){
    http.open("GET",paginas[i]+".html",true);
    http.onreadystatechange=function(){
        if(http.readyState==4){
            document.getElementById(paginas[i]).innerHTML = http.responseText;
            if(i == 0){
                carrega_paginas(1);
            }
        }
    }
    http.send(null);
}
  • Note that this process is more expensive for the browser than solving everything by the server, not to mention that it is sensitive to the speed (and signal quality) of the network

  • @Jeffersonquesado Yes, but he doesn’t want to do it for the server.

  • That’s why I put as a "note" about your answer, so that the AP understands what problems to face and that future people who stop here know it too. I like to put information that the idea is not legal, as the author of this reply made clear in the infographic: https://answall.com/a/240835/64969

0

Javascript:

const ajax = (url, cb, data) => {
    const xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
        if (this.readyState == 4 && this.status == 200) cb(this.responseText);
    })
    xhr.open(data?"get":"post", url, true);
    xhr.setRequestHeader("Content-type:", "application/x-www-form-urlencoded");
    xhr.send(data);
}
ajax("header.php", conteudo => document.body.appendChild(conteudo));
  • I put this code inside a javascript file and use the last line to call the file where you want it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.