Home > database >  Is there a way to fetch record from db without reloading a page
Is there a way to fetch record from db without reloading a page

Time:03-20

How do I fetch my data i.e. movie names from my database on the click of button without refreshing my page ? I am building a Bingo game where I am trying to put an history record button to display my data in the context of a drop down Please refer to my below code and help!!!

--This is my history.php file

            <?php

            require_once 'config.php';
            ?>
            <!DOCTYPE html>
            <html>
            <style>
                #rec_mode{
                    background-image: url('register.png');
                    background-size: 100% 100%;
                    width: 100px;
                    height: 50px;
                    border: none;
                    outline: 0px;
                    -webkit-appearance: none;  
                }
            </style>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script>
            history_num_arr = [];
                // For showing latest image from host -- end 
                $(function () {
                    var latestNum;
                    history_num_arr = [];
                    var url = "fetch_num.php";
                    setInterval(function () {
                    tempArr = [];
                    $("#number").load(url);
                    imgNum = jQuery("#number").text();
                    // $("#PostIMG").attr("src", "movie poster/"   imgNum   ".jpg");

                    if (history_num_arr[history_num_arr.length - 1] != imgNum) {
                        history_num_arr.push(imgNum);
                        if (localStorage.getItem("history_num") === null) {
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                    }
                    else if ((history_num_arr.length === 1) && (localStorage.getItem("history_num") != null)) {
                            console.log("hello");
                            tempArr = JSON.parse((localStorage.getItem("history_num")));
                            history_num_arr = JSON.parse(JSON.stringify(tempArr));
                            console.log(history_num_arr);
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                    }
                    else if ((history_num_arr.length > 1) && (localStorage.getItem("history_num") != null)) {
                            console.log(history_num_arr);
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                        }
                    }
                }, 1000);
            });


                // For showing latest image from host -- end 
                $(document).ready(function () {
                    $("#historybtn").click(function () {
                        var url = "history.php";
                        $("#history").load(url);
                        alert(history_num_arr.join(' '));
                    });
                });
            </script>
            <script>
            var myobject = {
                // history : '$history_num_arr'
                };
            var select = document.getElementById("rec_mode");
            for(index in myobject) {
                select.options[select.options.length] = new Option(myobject[index], index);
            }

            </script>
            <body>
                
            <div id="histarr"></div>
            <div id="fetch">
                <p style="display: none;">
                <p style="display: none;" id="number"></p>
                </p>
            </div>
            <div id="history_num">
                <p style="display: none;">
                <p style="display: none;" id="history"></p>
                </p>
            </div>
                <!-- <button id="historybtn" onclick = "">History</button> -->
                <!-- <select name = "select_history" id="dropdown"> --> 
            <select name = "select_history" id="rec_mode">
            <option selected="true" disabled="disabled">
            <?php

            require_once 'config.php';

            // $hist = mysqli_query($mysqli, "SELECT name FROM `movie_names` ORDER BY movieID DESC");
            $hist = mysqli_query($mysqli,"SELECT m.name FROM movie_names m INNER JOIN host_table ht WHERE m.movieID = ht.random_num ORDER BY ID DESC");
            while ($row = $hist->fetch_assoc())
            {
                echo "<option value=\"select_history\">".$row['name']."</option>";
                // exit(0);
            }
            ?>
            </option>
            </select>
                <!-- </select> -->



            </body>
            </html>

-- This is my fetch_num.php file

            <?php 
            require_once 'config.php';
            // $sql = "SELECT  random_num FROM host_table ORDER BY ID DESC LIMIT 1;";
            $sql = "SELECT m.name FROM movie_names m INNER JOIN host_table ht WHERE m.movieID = ht.random_num ORDER BY ID DESC;";
            if($result = mysqli_query($mysqli,$sql)){
                if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_array($result)){ 
                        echo $row["name"];

                    }
                }
            }
            else{
                echo "Error".mysqli_error($mysqli);
            }
            ?>

--This is my config.php file

            <?php

                //Connecting to Database
                $host ="localhost";
                $user = "root";
                $pass ="";
                $db = 'randomized';

                //Creating a connection object
                $mysqli = mysqli_connect($host, $user, $pass, $db);
                echo "<br>";

                if (!$mysqli){
                die("Sorry we failed to connect: ". mysqli_connect_error());
                }
                else{
                    // echo "Connection done!";
                }

            ?>

CodePudding user response:

You won't be able to dynamically load data after it's loaded through PHP, as the PHP is only run on the server when you load the page.

You'll have to use the fetch API to make a request using JavaScript.

For example:

async function loadRecords() {
  const records = await fetch('/records.php');
  return records;
}

See the MDN docs for information on the JavaScript fetch api. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

CodePudding user response:

If you want to fetch data from servers without reloading your webpage there is a very populair tool for that. It is called AJAX (Asynchronous Javascript XML). You could create a seperate PHP file that handles the requests and then you can fetch the data from there via an AJAX request. Because you're using JQuery it could look something like this:

$.ajax({url: /* your php file path */, type="POST", data: {data: /* request information */})
    .done(function(response){
        /* do some DOM manipultion with the response here */
    }
    .fail(function(response){
        console.log(response);
        /* standard function for catching errors */
    }         
  • Related