Uncaught SyntaxError: Unexpected token u in JSON at position 0
I have an array that I take from localStorage using the following code
function loadCart(data) {
//проверяю есть ли в localStorage запись cart
if (localStorage.getItem('cart')) {
// если есть - расширфровываю и записываю в переменную cart
cart = JSON.parse(localStorage.getItem('cart'));
if(isEmpty(cart)){
$('.main-cart').html('Корзина пуста');
}
else init();
}
else {
$('.main-cart').html('Корзина пуста');
}
}
After that, I load an associative array with products from the database
function init(){
$.post(
'pages/adminPage/core.php',
{
"action":"loadGoods"
},
showCart
);
}
And I withdraw the product from localStorage
function showCart(data) {
var pack= JSON.parse(data);
var out = '';
for (var id in cart) {
for (key in pack) {
if(id===pack[key].id){
out += `<button data-id="${id}" class="del-goods">x</button>`;
out += `<img src="pages/orderPage/goods/${pack[key].img}"
width='50em' height='50em'>`;
out += ` ${pack[key].name }`;
out += ` <button data-id="${id}" class="minus-goods">-
</button> `;
out += ` ${cart[id]} `;
out += ` <button data-id="${id}" class="plus-goods">+
</button> `;
out += cart[id]*pack[key].cost;
out += '<br>';
}
}
}
$('.main-cart').html(out);
$('.del-goods').on('click', deleteGoods);
$('.plus-goods').on('click', plusGoods);
$('.minus-goods').on('click', minusGoods);
}
The problem is that when I perform the function minusGoods
function minusGoods(){
//уменьшает товар в корзине на 1
var id = $(this).attr('data-id');
if (cart[id]===1){
delete cart[id];
}
else cart[id]--;
saveCart();
showCart();
}
This error is thrown Uncaught SyntaxError: Unexpected token u in JSON at position 0 Most likely I'm doing it wrong, please tell me what it is problem
1 answers
showCart
called without parameters, so at runtime the value of the parameter data
- will be undefined
.
Next is an attempt to call
data=JSON.parse(data);
Which in this case is equivalent to
data=JSON.parse(undefined);
undefined
it is converted to a string "undefined"
- and an attempt is made to parse this string as JSON.
As a result, a natural mistake:
try {
JSON.parse('undefined');
} catch (e) {
console.log(e + '');
}
To solve it, you just need to pass the parameter to the function. Based on the provided code, something like:
showCart(cart[id]);
Either check whether a parameter is passed inside the function or not:
if(!isEmpty(cart) && data){
And as an alternative-to use different functions for init and normal work.