I am trying to create a shopping cart.
I have a function to add products in the cart :
jQuery('#shop-add-btn').click(function () {
modal.style.display = "block";
var Product = {
idProduct: jQuery(this).data('idproduct'),
name: jQuery(this).data('nameproduct'),
quantity: jQuery("#quantity").val(),
price: jQuery(this).data('price'),
poids: jQuery(this).data('poids')
};
addToShoppingCard(Product)
.done(function (data) {
if (data == 'true') {
getCountShippingCard().done(function (data) {
$('#cardCount').html(data);
});
alert('Produit ajouté');
} else {
alert(data);
}
});
});
So this function calls another function, addToShippingCard :
function addToShoppingCard(Product) {
return $.post(
'/app/plugin/shop/process/shipping.php',
{
ADDPRODUCTTOCARD: 'OK',
idProduct: Product.idProduct,
name: Product.name,
quantity: Product.quantity,
singlePrice: Product.price,
totalPoids: Product.quantity * Product.poids,
totalPrice: shop_financial(Product.quantity * Product.price)
});
}
But when I try to run it, I receive this error message from the console :
base_shop.js:104 Uncaught TypeError: Cannot read properties of undefined (reading 'post')
at getCountShippingCard (base_shop.js:104:14)
at Object.<anonymous> (e-billet-enfant-journee:415:25)
at fire (jquery-1.12.4.js:3232:31)
at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362:7)
at done (jquery-1.12.4.js:9840:14)
at XMLHttpRequest.callback (jquery-1.12.4.js:10311:8)
getCountShippingCard @ base_shop.js:104
(anonyme) @ e-billet-enfant-journee:415
fire @ jquery-1.12.4.js:3232
fireWith @ jquery-1.12.4.js:3362
done @ jquery-1.12.4.js:9840
callback @ jquery-1.12.4.js:10311
XMLHttpRequest.send (asynchrone)
send @ jquery-1.12.4.js:10254
ajax @ jquery-1.12.4.js:9738
jQuery.<computed> @ jquery-1.12.4.js:9890
addToShoppingCard @ base_shop.js:89
(anonyme) @ e-billet-enfant-journee:412
dispatch @ jquery-1.12.4.js:5226
elemData.handle @ jquery-1.12.4.js:4878
Can anyone help me and explain me what’s the problem here? Why doesn’t the navigator recognize the post function?
Thanks for your help
2
Answers
"Cannot read properties of undefined (reading ‘post’)" means the $.post function is not defined.
It is possible that the jQuery library is not properly loaded in your HTML file, or that it is being loaded after the base_shop.js file, so the $ object is not yet available when the base_shop.js file is being executed.
Try to import the "base_shop.js" file after jquery, for example, like so;
Alternatively, you can also try to this;
This ensures that the code in the base_shop.js file is only executed after the jQuery library has been loaded and the $ object is available.
JQuery is probably in compatibility mode to avoid conflict with other javascript libraries. Thus it is not loaded in DOM when you are using
$
sign.We can have JQuery like the following:
In your case, you need to choose safe JQuery approach.