php – Constant loading of data from the database

Question:

the form has a structure (table) and a form with fields for input. When the user enters information into the fields and presses the button, the data is added to the database and from there loaded into the structure. It is necessary to split the request so that the data, after clicking, is added to the database, and the structure (table) automatically loads the data into itself at some intervals from the database, without any clicks or actions. Here is the script code for the form:

    <form id="myform" action="for_db.php" method="post" >
                                    <div class="trading__buy-row">
                                        <div class="trading__buy-row-title">Price</div>
                                        <input type="text" id="price" name="price" class="priceField" onchange=f()>
                                        <div class="trading__buy-row-title2">111</div>
                                    </div>
                                    <div class="trading__buy-row">
                                        <div class="trading__buy-row-title">Amount</div>
                                        <input type="text" id="amount" name="amount" class="amountField" onchange=f()>
                                        <div class="trading__buy-row-title2">111</div>
                                    </div>
                                    <div class="trading__buy-row">
                                        <div class="trading__buy-row-title">Total</div>
                                        <input type="text" id="total" name="total" class="totalField" >
                                        <div class="trading__buy-row-title2">111</div>
                                    </div>
                                    <div class="trading__buy-text">Trade commission: <span>0.1%</span></div>
                                    <!--<div class="btn btn--buy" id="sub" >BUY</div> -->
                                    <input type="submit" value="Buy" class="button">
                                    <span id="result"></span>
                                </form>

                                <table class="rows"> 
                                </table>


                                <script type="text/javascript">
jQuery(document).ready(function() {
    jQuery(".button").bind("click", function() {

        var price = jQuery('.priceField').val();
        var amount = jQuery('.amountField').val();
        var total = jQuery('.totalField').val();

        jQuery('.priceField').val('');
        jQuery('.amountField').val('');
        jQuery('.totalField').val('');

        jQuery.ajax({
            url: "for_db.php",
            type: "POST",
            data: {price:price, amount:amount, total: total}, // Передаем данные для записи
            dataType: "json",
            success: function(result) {
                if (result){ 
                    jQuery('.rows tr').remove();
                    jQuery('.rows').append(function(){
                        var res = '';
                        for(var i = 0; i < result.ordersbuy.total.length; i++){
                            res += '<tr><td>' + result.ordersbuy.id[i] + '</td><td>' + result.ordersbuy.price[i] + '</td><td>' + result.ordersbuy.amount[i] + '</td><td>' + result.ordersbuy.total[i] + '</td></tr>';
                        }
                            return res;
                    });
                    console.log(result);
                }else{
                    alert(result.message);
                }
                return false;
            }
        });
    return false;
    });
});
</script>

Файл for_db.php:

<?php
 session_start();
    include_once('db.php');
    if (isset($_SESSION['userid'])) {
         $sesion_id=$_SESSION['userid'];
    }

$price = $_POST['price'];
$amount =$_POST['amount'];
$total = $_POST['total'];


/** Если нам передали ID то обновляем */
if($price && $amount && $total){
    //вставляем запись в БД
$mysqli->query("INSERT INTO `ordersbuy` (`id`,`price`,`amount`,`total`) VALUES ('$sesion_id','$price','$amount','$total')");
$query2 = $mysqli->query("SELECT * FROM `ordersbuy` ORDER BY `id` DESC");
    while($row = $query2->fetch_assoc()){
        $ordersbuy['id'][] = $row['id'];
        $ordersbuy['price'][] = $row['price'];
        $ordersbuy['amount'][] = $row['amount'];
        $ordersbuy['total'][] = $row['total'];
    }
    $message = 'Все хорошо';
}else{
    $message = 'Не удалось записать и извлечь данные';
}

/** Возвращаем ответ скрипту */

// Формируем масив данных для отправки
$out = array(
    'message' => $message,
    'ordersbuy' => $ordersbuy
);

// Устанавливаем заголовот ответа в формате json
header('Content-Type: text/json; charset=utf-8');

// Кодируем данные в формат json и отправляем
echo json_encode($out);
?>

Answer:

I once used such a function, in it I used

setInterval(() => {
  Функция, которая отправляет ajax запрос, и в нём обработчик ответа
}, промежуток отправления запроса)

I had a chat that showed new messages without refreshing the page

Scroll to Top