0

I am writing a simple shop in PHP (as a practice). I want to add functionality, that when I click the submit button, ToastR is shown: "Product successfully added to cart".

I am new to PHP.

The problem is, that form get submited (and page refreshed) and toastR doesn't have a chance to be shown. Can you suggest any solution to this problem?

Sample code:

<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
    <div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
        <div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
        <div>
            <input type="text" name="quantity" value="1" size="2"/>
            <input id="addToCartButton" type="submit" value="Add to cart" class="btnAddAction" onclick="toastr.info('Page Loaded!')"/>
        </div>
</form>

I add all neccessary css and js (toastR is working in other places)

Marek
  • 3,935
  • 10
  • 46
  • 70
  • Submit the form via ajax, and parse the response to show the ToastR notification? – circusdei Apr 25 '16 at 19:24
  • Could you please write the answer on how can I submit it via ajax? Or anyone else? – Marek Apr 25 '16 at 19:25
  • It would require a change in your architecture. You'l need an API endpoint to POST the "add to cart" information to via ajax. This can be written in PHP. You will also need the JS to make the ajax call, and something to parse the response. Here's a general how-to: http://www.sitepoint.com/use-jquerys-ajax-function/ – circusdei Apr 25 '16 at 19:27

1 Answers1

0
$( "form" ).submit(function( event ) {
    event.preventDefault();
    $this = $(this);
    $.post($this.attr("action"), function( data ) {
        //manage data returned
        toastr.info('Page Loaded!');
    });
});

This is an example of send post ajax call with jquery. Then manage your post request in php destination file. To complete the kind of post method, here you have some examples your toastr function will be called after the reload page.

Borja Tur
  • 779
  • 1
  • 6
  • 20