0

So i have a form that that does a simple calculation, depending on the users input. If the results is a certain value then it stores that value in a database, then it displays that value on a page. But i have to refresh the whole page for it to retrieve the latest updated value from the the database and display on the page.

I know how to write code to refresh the whole page, but in this case i only need the section where the it displays to be refreshed.

The original form to calculate

  <div class="formC">
     <form action="" method="post">
        <label>Base Amount</label>
            <input type="text" name="base"</input>
                <label>Select Currency</label>
        <div class="custom-select">
           <span></span>
           <select name="cur_name">
              <option value="" selected>Choose a Base Currency</option>
              <option value="EUR">EUR</option>
              <option value="USD">USD</option>
           </select>
        </div>
        <button type="submit" value="Submit">SUBMIT</button>
     </form>
  </div>

The form that gets the new values from the database

<div class="formC">
     <form action="test.php" method="post">
        <label>Base Amount</label>
        <input type="text" name="base" id="new_base" value="<?php
              $results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
              while($row = mysqli_fetch_array($results)){

              echo $row["new_base"];
              } 

              ?>">
         <div id="load_data"></div>
         <label>Select Currency</label>  
            <input type="text" name="cur_name" value="<?php 
            $results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
                 while($row = mysqli_fetch_array($results)){
                    echo $row["gain_name"];
                 }
            ?>">
        <button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
     </form>
  </div>

Calculation

<?php 
$base = $_POST['base'];
$value = $_POST['val'];
$selected = $_POST['cur_name'];

if ($selected == 'EUR') {   
    $results_eur = $base * $value;
    // USD
 }elseif ($selected == 'USD') {      
     $results_usd = $base * $value;
 }

 if($selected == 'EUR'){
    $sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
    mysqli_query($con,$sql);
 }elseif($selected == 'USD'){
    $sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
    mysqli_query($con,$sql);
 }
ADyson
  • 57,178
  • 14
  • 51
  • 63
MyNameJeff
  • 79
  • 7
  • 3
    And what's your question about this? Why not use `mysqli_insert_id` to read the latest inserted ID? Also, please use prepared statements to avoid getting hacked. – Nico Haase Apr 19 '22 at 11:25
  • 4
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Apr 19 '22 at 11:26
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Apr 19 '22 at 11:26
  • 3
    Anyway if you want to do a partial refresh of a page, first you need to learn about AJAX and how to use it. Take some tutorials if you haven't done it before. I'd recommend learning the syntax for the latest `fetch()` library which provides this functionality, rather than anything older. – ADyson Apr 19 '22 at 11:27
  • Are you asking about this? header("Refresh:0"); – Vishal Kalansooriya Apr 19 '22 at 11:30
  • 1
    @VishalKalansooriya that would just automate a full refresh of the page. OP wants a partial refresh, as they specifically stated. Therefore AJAX is the solution. – ADyson Apr 19 '22 at 11:46
  • @ADyson Ah ok got it thanks :) – Vishal Kalansooriya Apr 19 '22 at 11:47
  • Hi Guys, thank you for your responses. I managed to find the solution. As @ADyson explained, using AJAX worked perfectly for this. I updated the post. Could not post an Answer as they closed my post. – MyNameJeff Apr 20 '22 at 06:26
  • 1
    Glad you sorted it. I voted to re-open so if it gets more voted and is opened, you can post your answer properly :-) – ADyson Apr 20 '22 at 06:44

2 Answers2

2

I managed to find the solution for this code using Ajax and jQuery:

    $(document).ready(function(){
        $('#btn_submit').click(function(){
            var get_data = $('#new_base').val();
            
            if($.trim(get_data) != '')
                {
                    $.ajax({
                        url:"db2.php",
                        method:"POST",
                        data:{new_base:get_data},
                        dataType:"text",
                        success:function(data)
                        {
                            $('#new_base').val("");
                        }   
                    });     
                }   
        });         
        setInterval(function(){
            $('#load_data').load("fetch.php").fadeIn("slow")
        }, 1000);
    }); 
MyNameJeff
  • 79
  • 7
-3

This can be done by creating a seperate php file and replacing the content on your page with the content of that other php page using javascript. This is not a full description on how to do it, just a hint on how this is done. There are plenty of resources where it is described in detail. One place to start could be here W3Schools Ajax & Php

getData.php

header('Content-Type: application/json; charset=utf-8');

// do your php database stuff here
$data = //...

$data = json_encode($data);

echo $data;

And in your main file, you can fetch() the content of your getData.php in javascript to get the latest result and then inject the results into your div using document.getElementById('content').innerHTML = ...

Using this method, only your div refreshed, not the whole page.

Laisender
  • 714
  • 1
  • 5
  • 10
  • 2
    Neither this answer nor you other answer really describes well the process and processing involved in an AJAX conversation, which is the part the OP would need the most help with – RiggsFolly Apr 19 '22 at 11:33
  • Thats correct but that wasn't my intention at all. There are plenty of resources on this topic out there. I just wanted to hint OP in the right direction. – Laisender Apr 19 '22 at 11:41
  • 1
    Hi, if you want to HINT at something, use a COMMENT – RiggsFolly Apr 19 '22 at 11:42
  • 1
    Also downvoted for recommending the cesspit of misinformation, outdated content, errors and poor security practices which is w3schools. – ADyson Apr 19 '22 at 11:47