Skip to content

Commit

Permalink
use fetch when adding item to cart rather than submit form
Browse files Browse the repository at this point in the history
  • Loading branch information
isakgranqvist2021 committed Mar 29, 2022
1 parent 07d8648 commit f02da36
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 7 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
.env
/client/node_modules
/src/public/js
/client/node_modules
26 changes: 22 additions & 4 deletions src/controllers/cart/add-to-cart.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cart

import (
"fmt"
"strconv"

"github.com/gofiber/fiber/v2"
Expand All @@ -12,20 +13,37 @@ func AddToCart(c *fiber.Ctx) error {
var newItem models.CartItem

if err := c.BodyParser(&newItem); err != nil {
return c.Redirect("/error")
fmt.Println(err)
return c.JSON(fiber.Map{
"message": "Invalid request body",
"success": false,
"data": nil,
})
}

productId, err := strconv.ParseInt(c.Params("ID"), 10, 64)

if err != nil {
return c.Redirect("/error")
return c.JSON(fiber.Map{
"message": "Invalid query parameter",
"success": false,
"data": nil,
})
}

newItem.ID = int(productId)

if err := cart.AddToCartAndUpdateSession(c, newItem); err != nil {
return c.Redirect("/error")
return c.JSON(fiber.Map{
"message": "Item has not been added to cart",
"success": false,
"data": nil,
})
}

return c.Redirect(string(c.Context().Referer()))
return c.JSON(fiber.Map{
"message": "Item has been added to cart",
"success": true,
"data": nil,
})
}
2 changes: 1 addition & 1 deletion src/models/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ package models

type CartItem struct {
ID int
Quantity int
Quantity int `json:"quantity"`
}
92 changes: 92 additions & 0 deletions src/public/js/add-to-cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
primary,
success,
warning,
danger
*/

/*
element: string;
className: string,
attributes: {
key: string;
value: string;
}[];
*/
const createElement = (options) => {
if (!options.element) return null;

const element = document.createElement(options.element);

if (options.className) {
element.className = options.className;
}

if (options.attributes && options.attributes.length > 0) {
options.attributes.forEach((attribute) => {
element.setAttribute(attribute.key, attribute.value);
});
}

if (options.text) {
element.textContent = options.text;
}

return element;
};

const appendAlert = (text, severity) => {
if (!text) return;

const alertContainer = document.getElementById('alert-container');

Array.from(alertContainer.children).forEach((child) => {
alertContainer.removeChild(child);
});

const alertElement = createElement({
element: 'div',
className: 'uk-alert-' + severity,
attributes: [{ key: 'uk-alert', value: '' }],
});

alertElement.appendChild(
createElement({
element: 'a',
className: 'uk-alert-close',
attributes: [{ key: 'uk-close', value: '' }],
})
);

alertElement.appendChild(createElement({ text, element: 'p' }));

alertContainer.appendChild(alertElement);
};

const addToCart = async (productId) => {
const addToCartButton = document.getElementById('add-to-cart');

addToCartButton.setAttribute('disabled', true);

try {
const quantityInput = document.querySelector('[name=quantity]');

const quantity = parseInt(quantityInput.value);

const res = await fetch('/add-to-cart/' + productId, {
method: 'POST',
body: JSON.stringify({ quantity }),
headers: {
'Content-Type': 'application/json',
},
});

const data = await res.json();

appendAlert(data.message, data.success ? 'success' : 'danger');
} catch (err) {
return;
}

addToCartButton.removeAttribute('disabled');
};
7 changes: 7 additions & 0 deletions src/views/pages/view-product.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,18 @@ <h4>{{ .Product.Amount }} SEK</h4>
<option value="3">3</option>
</select>
<button
type="button"
id="add-to-cart"
onclick="addToCart('{{ .Product.ID }}')"
class="uk-margin-medium-left uk-button uk-button-primary uk-width-1-1"
>
Add to cart
</button>
</form>

<div id="alert-container" class="uk-margin-top"></div>
</div>
</div>
</div>

<script src="/public/js/add-to-cart.js"></script>

0 comments on commit f02da36

Please sign in to comment.