Ajax returns own code and executes

1

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

    <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 this using Ajax . It is working, that is, it generates the selects . But above select comes the whole code of the function Ajax together as a string , which 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 searched the internet a lot and did not find anything like it. When there was was that for some reason the code was interpreted as a string , however in my case it was executed as well.

    
asked by anonymous 23.02.2015 / 15:46

1 answer

4

The problem is that you added this require :

require "ajax.js";

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

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

    
23.02.2015 / 16:00