1
Hello, my friends! Good evening!
I am a beginner in Javascript and I am faced with the following situation: I have a script called js widget. on my home page and this script performs a request in search of a "complementary" html, on a second page called php widget.. On this second page (widget.php) I have a Javascript function.
The problem is this... when I make the request with Xmlhttprequest, everything I need (html and js) is placed on my home page (I can see inspecting), but the function returns me the following error: Uncaught Referenceerror: test is not defined
That is, the function coming from the.php widget is written, but not executed. It follows the summary of my code:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Teste</title>
</head>
<body>
<script async="" src="https://meusite.com/widget.js"></script>
</body>
</html>
js widget.
url = 'https://meusite.com/widget.php';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var resp = this.response;
var el = document.querySelector('body');
var html = '<div>'+resp+'</div>';
el.insertAdjacentHTML('beforeend', html);
}
};
xhr.open('GET', url, true);
xhr.send();
php widget.
<h1>Título</h1>
<p>Descrição</p>
<button onclick="teste();">Ok</button>
<script type="text/javascript">
function teste() {
alert('Ok!');
}
</script>
Follow the return images.
When loading:
After calling the function manually:
One important thing: I can’t use jQuery. In fact, I’ve tried it and it works very well. It needs to be with pure Javascript. I’ve also tried it with innerHTML and Eval(), and I couldn’t make it work.
So that’s it, guys. Does anyone know why this is happening and how can I fix it? Thank you all very much!
Tag
<script type="text/javascript">
remove the attributetype="text/javascript"
in HTML5 suffice<script>
– Augusto Vasques
Change the import form of these files bro.
– Felipe Henrique Monteiro Silve