shawnkauffman
shawnkauffman

Reputation: 139

Make Ajax and PHP update page without page refresh?

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);

Upvotes: 2

Views: 1576

Answers (3)

Vicky Dev
Vicky Dev

Reputation: 2173

As apparent as it could be, you don't have anything for when Ajax request succeeds(state == 200).

First you should look into this documentation for getting the idea of how jquery's ajax method works, also refer below links for the same:

http://www.sitepoint.com/use-jquerys-ajax-function/

http://www.w3schools.com/jquery/ajax_ajax.asp

You have to specify what you need to be done as soon as the jquery.ajax method is successfull or when it has completed it's execution. Mainly you have to specify what you need to do with data you get at the end of execution of the same method, generally you would show that data you got, to a specified section in the same page or you would build the whole page to reflect the changes made with ajax.

Upvotes: 0

David
David

Reputation: 218877

You're not actually doing anything to the page after the AJAX call completes. For example:

$.ajax({
    type: "POST",
    url: "index.php",
    data: { 
        bill_amount: billAmount, 
        bill_name: billName,
        action: 'addBill'
    },
    success: function (data) {
        // update the page somehow
    },
    error: function () {
        // there was an error, handle it here
    }
});

The page isn't going to automatically know how it should be updated. You have to write the code in that function to do it. Likely by identifying some page elements and modifying their contents, adding/removing other page elements, etc.

Upvotes: 1

Zapp
Zapp

Reputation: 232

You arent telling it to do anything after the ajax returns. Replace your .ajax call with this.

$.post( "index.php", { action: "add bill", time: "2pm" })
  .done(function( data ) {
    alert( "Data Loaded: " + data );
  });

Then you can replace the alert with w.e you were trying to do.

Upvotes: 0

Related Questions