Calling a PHP function with the Xmlhttprequest object( )

Asked

Viewed 118 times

0

I have this script.

function execultaAjax() {
    var fld_busca = document.getElementById("id_busca").value;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
            this.responseText;
        }
    };
    xhttp.open("POST", "busca.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("fld_busca="+fld_busca);
}

However, it executes all the php code of the.php file. I would like to organize my querys into functions and perform them only when necessary and not all at once.

This is the search.php file

<?php
      require 'config.php';
      require 'conection.php';
      require 'dataBase.php';

        $fld_busca = isset($_POST["fld_busca"]) ? $_POST["fld_busca"] : "";
        $sql = "SELECT * FROM tbl_ativo WHERE nome LIKE '%$fld_busca%' ORDER BY nome ASC";
        $retorno = executaQuery ($sql);
        while ($linha = mysqli_fetch_assoc($retorno)) $data [] = $linha;
        foreach ($data as $value) {
            echo "<option value= \"$value[id]\" > $value[nome] </option>";
          }
?>
  • Did my answer work? Or did I misunderstand?

1 answer

0


You can send the functions you want to perform by request:

xhttp.send("fld_busca="+fld_busca+"&functions=query1,query2,query3");
//                                  ^ execute as funções query1, query2, query3

In the php you can do something like this:

    require 'config.php';
    require 'conection.php';
    require 'dataBase.php';

   $fld_busca = isset($_POST["fld_busca"]) ? $_POST["fld_busca"] : "";
   $functions = isset($_POST["functions"]) ? explode(",",$_POST["functions"]) : false;

   if($functions === false) // se não foi postada as funções
      executaQuery ($sql); // executa uma query padrão
   else 
       foreach($functions as $function) // recupera as funções
            if(function_exists($function)) // se a função estiver declarada
                $function($fld_busca);  // execute-a    


   function query1($fld_busca){
       // faça algo
   }

   function query2($fld_busca){
       // faça algo
   }

   function query3($fld_busca){
       // faça algo
   }

But then you need to shape the solution to your need.

Browser other questions tagged

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