I\'m trying to create a javascript cart for a prototype project I\'m working on. I realise that in this situation an MVC framework like Angular/Knockout etc would be absolut
Rendering process of Products from Server.
function productSocket(doneFn,params){
$.ajax({
type:'GET',
url: "http://localhost:8080/"+params,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(doneFn)
.fail(function(err){
console.log("AJAX failed: " + JSON.stringify(err, null, 2));
});
}
function productDoneFn(data){
console.log("Okey done"+JSON.stringify(data));
var productContainer=$('#productContainer');
productContainer.empty();
var productContent="";
$.each(data ,function(i,e){
productContent+=''+
''+
''+
''+
'
'+
''+
''+
''+
''+e.nameEn+'
'+
'$'+e.price+'
'+
''+
''+
''+
'';
});
productContainer.html(productContent);
}
Here is an element like button for adding an item to the Cart and appropriate attributes for saving in Web Storage like localStorage.
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array the result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},
{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},
{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
After this action you can easily send data to server as List in Java.