Ajax returns own code and executes

Asked

Viewed 47 times

1

I have a page that should generate selects by clicking on the icon of +.

    <div class='form-group' id='div_selects'>
                <label for='materiais_defeito'>Material com defeito?</label>&nbsp&nbsp<i href="#" class="fa fa-plus fa-2x" onclick="gerarSelect()"></i>
            </div>

I did it using Ajax. It is working, that is, generates the selects. But above the select comes all function code Ajax along as a string, that is:

   function gerarSelect() 
    {
var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var newElement = document.createElement('div');
        newElement.innerHTML = xmlhttp.responseText;
        document.getElementById("div_selects").appendChild(newElement);
    }

}

xmlhttp.open("GET","../ajax/gerar_selects.php",true);
xmlhttp.send();

 }

The php that generates the selects is:

    <?php
session_start();
if(!$_SESSION["logado"])
    header("Location:../views/login_tela.php");


require "../bd/conecta_banco.php";
require "ajax.js";

$produtos = $con->query("SELECT * FROM produtos WHERE visibilidade = 'visivel'");

echo "<select class='form-control'>";

while ($produto = $produtos->fetch_object()) 
    echo "<option value='".$produto->id."'>".$produto->modelo."</option>";

echo "</select>";

 ?>

I’ve searched a lot on the internet and found nothing like it. When there was that for some reason the code was interpreted as a string, but in my case he was also executed.

1 answer

4

The problem is you added this require:

require "ajax.js";

PHP tries to interpret the contents of this file, but as there is no tag <?php it prints everything as if it were pure HTML.

JS files should be included only through the tag script in HTML.

  • Clear and direct kkk +1

  • That was me. Thank you guys!

Browser other questions tagged

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