Whenever I submit the "Add Bill" form, nothing happens until I refresh the page. That's when I see my new item in the Twig loop. The same problem happens when I click on the Remove link. Nothing is removed (visually) until I refresh the page.
How do I make this stuff happen right away on the page without a page refresh? I'm thinking it might have something to do with my PHP or SQL?
JavaScript:
$(document).ready(function() {
$(".addBill").on("click", function() {
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
bill_amount: billAmount,
bill_name: billName,
action: 'addBill'
}
});
return false;
});
$(".removeBill").on("click", function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "index.php",
data: {
id_to_delete: id,
action: 'removeBill'
}
});
return false;
});
});
HTML:
<form method="post" name="addBillForm">
<input type="text" placeholder="Enter bill name" name="billName" class="billName">
<input type="text" placeholder="Enter bill amount" name="billAmount" class="billAmount">
<input type="submit" value="Submit" name="addBillForm" class="addBill">
</form>
<br><br>
<h2>My Bills</h2>
{% for bill in bills %}
<p>{{ bill.billName }} - {{ bill.billAmount }} -
<a href="#" class="removeBill" data-id="{{ bill.id }}">Remove</a>
</p>
{% endfor %}
Here is my PHP file:
<?php
require_once 'global.php';
if (@$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
if (@$_POST['action'] == 'removeBill')
{
$id = intval($_POST['id_to_delete']);
$stmt = $db->prepare("DELETE FROM bills WHERE id = ?");
$stmt->bindValue(1, $id);
$stmt->execute();
}
$billResults = $db->query('SELECT * FROM bills');
$bills = $billResults->fetchAll(PDO::FETCH_ASSOC);
$twigContext = array(
"bills" => $bills
);
echo $twig->render('base.html.twig', $twigContext);