AJAX - Requests made before the event occurs (executing action before the click)

Asked

Viewed 6 times

0

I am developing a school system, using Php as a back-end language.
I have a registered users query page, which initially opens listing all existing registrations, however there is a checkbox filter that, according to the positions that the user selects, will list only users of such positions.
This must be done asynchronously, so I’m using techniques AJAX for this solution.

Thus, I used a repeating structure that passes in all checkboxes and adds an Eventlistener that by clicking in a checkbox, the function makeRequest() that makes the HTTP request is called.
But the request is being made 5 times (total of checkboxes) without clicking on any checkbox, just by loading the page.
What might be going on?

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SIEGE - Registros </title>
    <link rel="stylesheet" type="text/css" href="CSS/reset.css">
    <link rel="stylesheet" type="text/css" href="CSS/forms.css">
    <link rel="stylesheet" type="text/css" href="CSS/texto.css">
    <link rel="stylesheet" type="text/css" href="CSS/user_main.css">
    <script src="JS/filtro_pesquisa_usuario.js" defer></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>

<body>
    
    <?php
        include ('componentes/user_nav.php');
    ?>

    <h1 class="titulo-principal centralizar-texto" style="margin-bottom: 25px;">Funcionários cadastrados</h1>

    <form class="user" action="#" method="post">
        <label>Marque o tipo de funcionário que gostaria de ver os registros:</label> <br><br>

        <input type="checkbox" class="cargoFiltro" id="dir" name="dir" value="diretor">
        <label for="dir"> Diretor(a) e Vice</label>

        <input type="checkbox" class="cargoFiltro" id="secr" name="secr" value="secretario">
        <label for="secr"> Secretário(a)</label>

        <input type="checkbox" class="cargoFiltro" id="sup" name="sup" value="supervisor">
        <label for="sup">Supervisor(a)</label>

        <input type="checkbox" class="cargoFiltro" id="prof" name="prof" value="professor">
        <label for="prof">Professor(a)</label>

        <input type="checkbox" class="cargoFiltro" id="alu" name="alu" value="aluno">
        <label for="alu">Aluno(a)</label><br>
    </form>
    <br><br>

    <?php
        include ("CRUD/Usuario/read.php");
    ?>

</body>

</html>
var httpRequest;

var options = document.getElementsByClassName('cargoFiltro');

for (let i = 0; i < options.length; i++) {
    var checkbox = options[i];
    checkbox.addEventListener("click", makeRequest());
}

function makeRequest() {
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) { }
        }
    }

    if (!httpRequest) {
        alert("Desistindo: Não é possível criar uma instância XMLHTTP.");
        return false;
    }
    httpRequest.open('GET', 'CRUD/Usuario/readFiltro.php');
    httpRequest.responseType = "json";
    httpRequest.send();
    httpRequest.addEventListener("readystatechange", function () {

        if (httpRequest.readyState === 4 && httpRequest.status === 200) {
            alert("Deu certo!");
        }

    });
}
No answers

Browser other questions tagged

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