简体   繁体   中英

How to fetch data from database based on user input and display as JSON array using asynchronous POST in php

I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).

index2.php

<?php

class logAgent
{
    const CONFIG_FILENAME = "data_config.ini";

    private $_dbConn;
    private $_config;

    function __construct()
    {
        $this->_loadConfig();


        $this->_dbConn = oci_connect($this->_config['db_usrnm'],
            $this->_config['db_pwd'],
            $this->_config['hostnm_sid']);
    }
    private function _loadConfig()
    {
        // Loads config
        $path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
        $this->_config = parse_ini_file($path) ;
    }
    public function fetchLogs() {

        $sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
                            FROM AUTH_LOGS WHERE USERID = '".$uid."'";

        //Preparing an Oracle statement for execution
        $statement = oci_parse($this->_dbConn, $sql);

        //Executing statement
        oci_execute($statement);
        $json_array = array(); 

        while (($row = oci_fetch_row($statement)) != false) {
            $rows[] = $row;
            $json_array[] = $row; 
        }
            json_encode($json_array);   
    }

}

$logAgent = new logAgent();
$logAgent->fetchLogs();
?>

I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.

<!DOCTYPE html>
<html>
    <head>
        <title>User_Logs</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="script.js"></script>
    </head>

    <body>
    <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST"){
            $uid =$_POST["USERID"];

        }
        ?>
        <form method="POST" id="form-add" action="index2.php">
            USER_ID: <input type="text" name="USERID"/><br>
            <input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
        </form>
    </body>
</html>

My script:

$(document).ready(function(){
    $("#mybtn").click(function(){
        $.POST("index2.php", {
            var myVar = <?php echo json_encode($json_array); ?>;
        });

        });
})

This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST . How can i do that? I have never done this asynchronous POST coding. Kindly help.

i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.

 $(document).ready(function(){ $("#mybtn").click(function(e){ e.preventDefault(); $.post("index2.php", {data :'<?php echo json_encode($json_array);?>' }) }); }) 

I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.

$(document).ready(function(){
    $("#mybtn").click(function(e){
        e.preventDefault();
        $.POST("index2.php", {
            var myVar = "<?php echo json_encode($json_array); ?>";
        });

        });
})

you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)

Can you try this,

$(document).ready(function(){
   $("#mybtn").click(function(event){
      event.preventDefault();  
      $.POST("index2.php", {
          var myVar = <?php echo json_encode($json_array); ?>;
    });

  });
});

Also in HTML remove action in form

<form method="POST" id="form-add">
    USER_ID: <input type="text" name="USERID"/><br>
    <input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>

Edit : Can you try this please ? Second param for post takes an object .

 $(document).ready(function(){
        $("#mybtn").click(function(event){
        event.preventDefault();  
            var myVar = <?php echo json_encode($json_array); ?>;
            console.log(myVar);
            $.post("submit.php", {
                'id': myVar
            },function(data){
                console.log(data);
            });
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM