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
JavaScript
x
17
17
1
<div class="formC">
2
<form action="" method="post">
3
<label>Base Amount</label>
4
<input type="text" name="base"</input>
5
<label>Select Currency</label>
6
<div class="custom-select">
7
<span></span>
8
<select name="cur_name">
9
<option value="" selected>Choose a Base Currency</option>
10
<option value="EUR">EUR</option>
11
<option value="USD">USD</option>
12
</select>
13
</div>
14
<button type="submit" value="Submit">SUBMIT</button>
15
</form>
16
</div>
17
The form that gets the new values from the database
JavaScript
1
23
23
1
<div class="formC">
2
<form action="test.php" method="post">
3
<label>Base Amount</label>
4
<input type="text" name="base" id="new_base" value="<?php
5
$results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
6
while($row = mysqli_fetch_array($results)){
7
8
echo $row["new_base"];
9
}
10
11
?>">
12
<div id="load_data"></div>
13
<label>Select Currency</label>
14
<input type="text" name="cur_name" value="<?php
15
$results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
16
while($row = mysqli_fetch_array($results)){
17
echo $row["gain_name"];
18
}
19
?>">
20
<button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
21
</form>
22
</div>
23
Calculation
JavaScript
1
20
20
1
<?php
2
$base = $_POST['base'];
3
$value = $_POST['val'];
4
$selected = $_POST['cur_name'];
5
6
if ($selected == 'EUR') {
7
$results_eur = $base * $value;
8
// USD
9
}elseif ($selected == 'USD') {
10
$results_usd = $base * $value;
11
}
12
13
if($selected == 'EUR'){
14
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
15
mysqli_query($con,$sql);
16
}elseif($selected == 'USD'){
17
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
18
mysqli_query($con,$sql);
19
}
20
Advertisement
Answer
I managed to find the solution for this code using Ajax and jQuery:
JavaScript
1
23
23
1
$(document).ready(function(){
2
$('#btn_submit').click(function(){
3
var get_data = $('#new_base').val();
4
5
if($.trim(get_data) != '')
6
{
7
$.ajax({
8
url:"db2.php",
9
method:"POST",
10
data:{new_base:get_data},
11
dataType:"text",
12
success:function(data)
13
{
14
$('#new_base').val("");
15
}
16
});
17
}
18
});
19
setInterval(function(){
20
$('#load_data').load("fetch.php").fadeIn("slow")
21
}, 1000);
22
});
23