Tuesday, 14 March 2017

Bind data and re-render DOM after AJAX call (express-handlebars)

I'm developing shopping cart as part of my learning.

Homepage enter image description here

It would be great if when users click on "Add to cart" button the total quantity of items in cart in header get binded and re-render without reloading the page.


What I'm doing now:

views/index.hbs

<header>
  <div>Shopping cart<span class="badge"></span><div>
</header>
  . . .
<a href="/add-to-cart/">Add to Cart</a>

routes/index.js

router.get('/', function(req, res, next) {

  Product.find()
    .exec(function (err, products) {
      res.render('index', { products: products});
  });
});

routes/cart.js

router.get('/add-to-cart/:id', function (req, res, next) {

  // access database and modify cart (update cart items quantity)
        req.session.cart = cart;
        res.redirect('/');
});

Currently, when "Add to cart" button is clicked, the page is reloaded. How do I send the AJAX call to modify the item quantity without reloading the page.


Possible solution:

Changing button from <a href="/add-to-cart/"> to <button> and handle click event by sending AJAX request to /add-to-cart/:id. But how to handle after that is question.


Note: I'm using "express-handlebars" modules i.e not just include handlebar.js in html.



via NERDYLIZARD

No comments:

Post a Comment