Delete data from json - javascript

I have a problem with delete object from my json file:
{
"data": [{
"index": "1",
"part": "15",
"dueDate": "2019-03-19"
}]
}, {
"data": [{
"index": "2",
"part": "22",
"dueDate": "2019-03-19"
}]
},
#edit
I add a javascript code. The function getTasks was displaying this json file in html site. So, maybe in here I should make a changes.
var todos = new Array();
var todo_index = 0;
window.onload = init;
function init() {
var submitButton = document.getElementById("submit");
submitButton.onclick = getFormData;
getTodoData();
}
function getTodoData() {
function request(method, url, data=null) {
return new Promise((resolve, reject)=> {
const xhr = new XMLHttpRequest;
xhr.timeout = 2000;
//xhr.responseType = 'json';
xhr.onreadystatechange = (e) => {
if(xhr.readyState === 4){
xhr.status === 200 ? resolve(xhr.response) : reject(xhr.status)
}
}
xhr.ontimeout = () => reject('timeout');
xhr.open(method, url, true);
if(method.toString().toLowerCase() === 'get') {
xhr.send(data)
} else {
xhr.setRequestHeader('Accept','application/json');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(data)
}
})
}
async function getTasks(){
const task = await request('GET', '/WebService/todo.json');
document.getElementById("todoList").innerHTML=task
}
getTasks()
}
function parseTodoItems(todoJSON) {
if (todoJSON == null || todoJSON.trim() == "") {
return;
}
var todoArray = JSON.parse(todoJSON);
if (todoArray.length == 0) {
console.log("Error: Array is empty!");
return;
}
for (var i = 0; i < todoArray.length; i++) {
var todoItem = todoArray[i];
todos.push(todoItem);
}
}
function checkInputText(value, msg) {
if (value == null || value == "") {
alert(msg);
return true;
}
return false;
}
function Todo(index, part) {
this.index = index;
this.part = part;
}
function addTodosToPage() {
var table = document.getElementById("todoList");
var tr = document.createElement("tr");
var index = document.getElementById('index').value;
var part = document.getElementById('part').value;
tr.innerHTML = "<td>" + index + "</td><td>" + part + "</td>";
table.appendChild(tr);
todo_index++;
tr.id = "todo-" + todo_index;
var index = document.getElementById('index').value;
var part = document.getElementById('part').value;
tr.innerHTML = "\
<td><input name='select-row' type='checkbox' value='" + todo_index + "'></td>\
<td>" + index + "</td>\
<td>" + part + "</td>\
<td><button onclick='removeTodo(" + todo_index + ");'>x</button></td>";
table.appendChild(tr);
}
function getFormData() {
var index = document.getElementById("index").value;
var part = document.getElementById("part").value;
console.log("Index: " + index + " part: "+ part);
var todoItem = new Todo(index, part);
todos.push(todoItem);
addTodosToPage(todoItem);
saveTodoData();
}
function checkInputText(value, msg) {
if (value == null || value == "") {
alert(msg);
return true;
}
return false;
}
function saveTodoData() {
var todoJSON = JSON.stringify(todos);
var request = new XMLHttpRequest();
var URL = "save.php?data=" + encodeURI(todoJSON);
request.open("GET", URL);
request.setRequestHeader("Content-Type",
"text/plain;charset=UTF-8");
request.send();
}
function removeTodo(index) {
var row = document.getElementById('todo-' + index);
if (row) {
row.parentNode.removeChild(row);
}
todo_index--;
}
function toggleSelection(checkbox) {
var rowsToSelect = document.querySelectorAll('input[name=select-row]');
for (var i = 0; i < rowsToSelect.length; i++) {
rowsToSelect[i].checked = checkbox.checked;
}
}
function removeSelectedTodos() {
var rowsToRemove = document.querySelectorAll('input[name=select-row]:checked');
for (var i = 0; i < rowsToRemove.length; i++) {
removeTodo(rowsToRemove[i].value);
}
}
function setselection(){
var project = document.getElementById('todoList').value;
document.cookie = 'todotabel=' + project;
}
function getselection(){
var name = 'todotabela=';
var x = document.cookie.split(';');
var i = 0, c = 0;
for(i = 0; i < x.length; i++) {
c = x[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(selectedProject) === 0) {
return c.substring(name.length, c.length);
}
} return '';
}
function remove() {
var arr = [];
var obj = {
'index': document.getElementById("index").value
};
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i]['index'] === obj['index']) {
arr.splice(i, 1);
}
}
localStorage.removeItem("user", JSON.stringify(arr));
}
function appendLocalStorage(keys, data) {
var old = localStorage.getItem(index);
if (old === null) old = "";
localStorage.setItem(index, old + data);
}
function addTo() {
var arr = [];
var obj = {
'index': document.getElementById("index").value,
'part': document.getElementById("part").value,
};
if (!arr.some(e => e['index'] == obj['index'])) {
arr.push(obj);
} else {
arr[arr.map((e, i) => [i, e]).filter(e => e[1]['index'] == obj['index'])[0][0]] = obj;
}
appendLocalStorage("user", JSON.stringify(arr));
alert(localStorage.getItem("user"));
}
This data is saved from input file by php and javascript function
How can I delete one of objects in array? Etc. I want to delete object with index:2 And I need delete this by button in html. How can I do this?
My php file:
$unsafe_json = json_decode($_GET["data"], true);
if (!is_array($unsafe_json)) {
die('Error save');
}
$safe_json = ['data' => []];
$values = ['index', 'part', 'dueDate'];
foreach ($unsafe_json as $unsafe_todo) {
$safe_todo = [];
foreach ($values as $value) {
if (isset($unsafe_todo[$value]) && is_string($unsafe_todo[$value])) {
$safe_todo[$value] = filter_var($unsafe_todo[$value], FILTER_SANITIZE_STRING);
} else {
$safe_todo[$value] = false;
}
}
* /
$safe_json['data'][] = $safe_todo;
}
$file = fopen("todo.json", "a");
fwrite($file, '' . json_encode($safe_json) . ',');
fclose($file);
$data = file_get_contents('todo.json');

i think what you are looking for is
unset($OBJECT['INDEX']);
you can iterate through your JSON, and when you match you condition you can call PHP's unset() method to remove the index
*Update
Code sample to remove with php
$json_decoded = json_decode($json_encoded, true);
foreach ($json_decoded as $i => $object)
if ($object['data']['index'] == 2)
unset($json_decoded[$i]);

Related

SharePoint 2016 - JSLink - save not working with IE but working with Chrome

I've got a strange behaviour with a JSLINK I'm using on my SP. The save button of the form is not working with IE if I change the value of the field that the JSLINK is transforming but it's ok with Chrome.
The field is type of Multiline plain text. I'm using using to save some JSON.
Here is the code:
(function() {
var loaded = false;
var repeaterFormArr = [
"<input type='text' id='nameInput' placeholder='Nom complet' class='ms-long ms-spellcheck-true intervenantsBox' required>",
"<input type='text' id='addressInput' placeholder='Adresse' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='phoneInput' placeholder='Telephone' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='emailInput' placeholder='Email' pattern=\"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$\" title='xxx#yyy.zzz' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<select name='typeActor' id='typeActor' class='ms-long intervenantsBox'><option value='plaignant'>Plaignant</option><option value='avocat'>Avocat</option><option value='DPO'>DPO</option><option value='demandeur'>Demandeur</option></select>",
];
var ControlRenderModeIntervenant;
var repeaterFormValues = [];
function includeCss() {
if (loaded) return;
loaded = true;
var link = document.createElement('link');
link.href = _spPageContextInfo.siteAbsoluteUrl + '/Style%20Library/CSS/intervenantsEditCustom.css';
link.rel = 'stylesheet';
document.head.appendChild(link);
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledViewTemplate(ctx) {
ControlRenderModeIntervenant = ctx.ControlMode;
if (ctx.CurrentItem[ctx.CurrentFieldSchema.Name] && ctx.CurrentItem[ctx.CurrentFieldSchema.Name] != '[]') {
var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name].replace(/"/g, "\"").replace(/(<([^>]+)>)/g, "");
repeaterFormValues = JSON.parse(fieldValue);
}
return GetRenderHtmlRepeaterValuesIntervenants();
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledEditFTemplate(ctx) {
var field = ctx.CurrentFieldSchema,
encodedName = field.Name + '_' + field.Id + '_$NumberField';
ControlRenderModeIntervenant = ctx.ControlMode;
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
if (formCtx.fieldValue) {
repeaterFormValues = JSON.parse(formCtx.fieldValue);
}
// Register a callback just before submit.
ctx.FormContext.registerGetValueCallback(field.Name, function() {
return JSON.stringify(repeaterFormValues);
});
ctx.FormContext.registerInitCallback(field.Name, function() {
document.getElementById('innerFormIntervenants').addEventListener('submit', function(evt) {
evt.preventDefault();
AddIntervenant();
return false;
});
var deleteLinks = document.getElementsByClassName('delete-link');
if (deleteLinks.length > 0) {
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener("onclick", function(evt) {
evt.preventDefault();
DeleteItem(deleteLinks[i].getAttribute('data-myAttri'));
return false;
});
}
}
});
// formCtx.registerGetValueCallback(formCtx.fieldName, function() {
// return JSON.stringify(repeaterFormValues);
// });
var HTMLViewTemplate = "<form id='innerFormIntervenants'>{Controls}<div><input type='submit' value='Add' style='margin-left:0'></div><br/><div id='divRepeaterValues'>{RepeaterValues}</div><br/></form>";
var returnHTML = "";
for (index = 0; index < repeaterFormArr.length; ++index) {
returnHTML += repeaterFormArr[index];
}
returnHTML = HTMLViewTemplate.replace(/{Controls}/g, returnHTML);
returnHTML = returnHTML.replace(/{RepeaterValues}/g, GetRenderHtmlRepeaterValuesIntervenants());
return returnHTML;
}
function GetRenderHtmlRepeaterValuesIntervenants() {
var index;
var innerindex;
var HTMLItemsTemplate = "<table width='600px' style='border:1px solid #ababab;'>{Items}</table>";
var HTMLItemTemplate = "<tr>{Item}</tr>";
var HTMLValueTemplate = "<td>{Value}</td>";
if (ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.EditForm || ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.NewForm) {
HTMLItemTemplate = "<tr>{Item}<td><a class='delete-link' data-myAttri='{Index}' href='#'><img src='/SiteAssets/IMG/user-delete.png' class='deleteUserButton'/></a></td></tr>";
}
var returnHTML = "";
var tempValueHtml;
for (index = 0; index < repeaterFormValues.length; ++index) {
tempValueHtml = "";
for (innerindex = 0; innerindex < repeaterFormValues[index]["Intervenant"].length; ++innerindex) {
tempValueHtml += HTMLValueTemplate.replace(/{Value}/g, repeaterFormValues[index]["Intervenant"][innerindex]["Value"]);
}
returnHTML += HTMLItemTemplate.replace(/{Item}/g, tempValueHtml);
returnHTML = returnHTML.replace(/{Index}/g, index);
}
if (repeaterFormValues.length) {
returnHTML = HTMLItemsTemplate.replace(/{Items}/g, returnHTML);
}
return returnHTML;
}
function AddIntervenant() {
var innerFormIntervenants = document.getElementById('innerFormIntervenants');
if (innerFormIntervenants.checkValidity()) {
var index;
var tempRepeaterValue = [];
for (index = 0; index < innerFormIntervenants.length; index++) {
if (innerFormIntervenants[index].type != "submit" && innerFormIntervenants[index].type != "button" && innerFormIntervenants[index].type != "reset") {
tempRepeaterValue.push({
"ID": innerFormIntervenants[index].id,
"Value": innerFormIntervenants[index].value
});
innerFormIntervenants[index].value = "";
}
}
repeaterFormValues.push({ "Intervenant": tempRepeaterValue });
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
}
function DeleteItem(index) {
repeaterFormValues.splice(index, 1);
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.OnPreRender = includeCss;
overrideCtx.Templates.Fields = {
myCustomField: {
View: IntervenantsRepeaterFiledViewTemplate,
DisplayForm: IntervenantsRepeaterFiledViewTemplate,
NewForm: IntervenantsRepeaterFiledEditFTemplate,
EditForm: IntervenantsRepeaterFiledEditFTemplate
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
In Debug, I can see that the callback function is called. Then it goes inside the JS of SharePoint for saving the item. But the save button is just going to grey and then nothing append.

element null in Magento

I upgrade magento from 1.8.1 to 1.9.0, and I have a problem with one js file:
TypeError: $(...) is null
$('product_addtocart_form').getElements().each(function(el) {
simple_product_pricing.js (line 1131, col 5)
I think this file is related to the Ayasoftware_SimpleProductPricing, maybe someone can help me to solve this. Before upgrade in 1.8.1 version everything was fine, in 1.9.0 version I have this error.
I will add here the entire js:
/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
some of these functions were initially written by Matt Dean ( http://organicinternet.co.uk/ )
*/
Product.Config.prototype.getMatchingSimpleProduct = function(){
var inScopeProductIds = this.getInScopeProductIds();
if ((typeof inScopeProductIds != 'undefined') && (inScopeProductIds.length == 1)) {
return inScopeProductIds[0];
}
return false;
};
/*
Find products which are within consideration based on user's selection of
config options so far
Returns a normal array containing product ids
allowedProducts is a normal numeric array containing product ids.
childProducts is a hash keyed on product id
optionalAllowedProducts lets you pass a set of products to restrict by,
in addition to just using the ones already selected by the user
*/
Product.Config.prototype.getInScopeProductIds = function(optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var allowedProducts = [];
if ((typeof optionalAllowedProducts != 'undefined') && (optionalAllowedProducts.length > 0)) {
allowedProducts = optionalAllowedProducts;
}
for(var s=0, len=this.settings.length-1; s<=len; s++) {
if (this.settings[s].selectedIndex <= 0){
break;
}
var selected = this.settings[s].options[this.settings[s].selectedIndex];
if (s==0 && allowedProducts.length == 0){
allowedProducts = selected.config.allowedProducts;
} else {
allowedProducts = allowedProducts.intersect(selected.config.allowedProducts).uniq();
}
}
//If we can't find any products (because nothing's been selected most likely)
//then just use all product ids.
if ((typeof allowedProducts == 'undefined') || (allowedProducts.length == 0)) {
productIds = Object.keys(childProducts);
} else {
productIds = allowedProducts;
}
return productIds;
};
Product.Config.prototype.getProductIdOfCheapestProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var minPrice = Infinity;
var lowestPricedProdId = false;
//Get lowest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice < minPrice) {
minPrice = thisPrice;
lowestPricedProdId = productIds[x];
}
}
return lowestPricedProdId;
};
Product.Config.prototype.getProductIdOfMostExpensiveProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var maxPrice = 0;
var highestPricedProdId = false;
//Get highest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice >= maxPrice) {
maxPrice = thisPrice;
highestPricedProdId = productIds[x];
}
}
return highestPricedProdId;
};
Product.OptionsPrice.prototype.updateSpecialPriceDisplay = function(price, finalPrice) {
var prodForm = $('product_addtocart_form');
jQuery('p.msg').hide();
jQuery('div.price-box').show();
var specialPriceBox = prodForm.select('p.special-price');
var oldPricePriceBox = prodForm.select('p.old-price, p.was-old-price');
var magentopriceLabel = prodForm.select('span.price-label');
if (price == finalPrice) {
//specialPriceBox.each(function(x) {x.hide();});
magentopriceLabel.each(function(x) {x.hide();});
oldPricePriceBox.each(function(x) { x.hide();
// x.removeClassName('old-price');
// x.addClassName('was-old-price');
});
jQuery('.product-shop').removeClass('sale-product') ;
}else{
specialPriceBox.each(function(x) {x.show();});
magentopriceLabel.each(function(x) {x.show();});
oldPricePriceBox.each(function(x) { x.show();
x.removeClassName('was-old-price');
x.addClassName('old-price');
});
jQuery('.product-shop').addClass('sale-product') ;
}
};
//This triggers reload of price and other elements that can change
//once all options are selected
Product.Config.prototype.reloadPrice = function() {
var childProductId = this.getMatchingSimpleProduct();
var childProducts = this.config.childProducts;
var usingZoomer = false;
if(this.config.imageZoomer){
usingZoomer = true;
}
if(childProductId){
var price = childProducts[childProductId]["price"];
var finalPrice = childProducts[childProductId]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(true);
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
if(this.config.updateShortDescription) {
this.updateProductShortDescription(childProductId);
}
if(this.config.updateDescription) {
this.updateProductDescription(childProductId);
}
if(this.config.updateProductName) {
this.updateProductName(childProductId);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(childProductId);
}
this.showTierPricingBlock(childProductId, this.config.productId);
if (usingZoomer) {
this.showFullImageDiv(childProductId, this.config.productId);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(childProductId);
}
}
} else {
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice");
var price = childProducts[cheapestPid]["price"];
var finalPrice = childProducts[cheapestPid]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(false);
if(this.config.updateProductName) {
this.updateProductName(false);
}
if(this.config.updateShortDescription) {
this.updateProductShortDescription(false);
}
if(this.config.updateDescription) {
this.updateProductDescription(false);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(false);
}
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
this.showTierPricingBlock(false);
this.showCustomOptionsBlock(false, false);
if (usingZoomer) {
this.showFullImageDiv(false, false);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(false);
}
}
}
};
Product.Config.prototype.updateProductImage = function(productId) {
var imageUrl = this.config.imageUrl;
if(productId && this.config.childProducts[productId].imageUrl) {
imageUrl = this.config.childProducts[productId].imageUrl;
}
if (!imageUrl) {
return;
}
if($('image')) {
$('image').src = imageUrl;
} else {
$$('#product_addtocart_form p.product-image img').each(function(el) {
var dims = el.getDimensions();
el.src = imageUrl;
el.width = dims.width;
el.height = dims.height;
});
}
};
Product.Config.prototype.updateProductName = function(productId) {
var productName = this.config.productName;
if (productId && this.config.ProductNames[productId].ProductName) {
productName = this.config.ProductNames[productId].ProductName;
}
$$('#product_addtocart_form div.product-name h1').each(function(el) {
el.innerHTML = productName;
});
var productSku = this.config.sku ;
if (productId && this.config.childProducts[productId].sku) {
productSku = this.config.childProducts[productId].sku ;
}
jQuery('.sku span').text(productSku) ;
var productDelivery = this.config.delivery;
if (productId && this.config.childProducts[productId].delivery) {
productDelivery = this.config.childProducts[productId].delivery ;
}
jQuery('.delivery-info').html(productDelivery) ;
var productReturns = this.config.returns;
if (productId && this.config.childProducts[productId].returns) {
productReturns = this.config.childProducts[productId].returns ;
}
jQuery('.returns-info').html(productReturns) ;
var productDownloads = this.config.downloads;
if (productId && this.config.childProducts[productId].downloads) {
productDownloads = this.config.childProducts[productId].downloads;
}
if (productDownloads) jQuery('.downloads-info').html(productDownloads) ;
else jQuery('.downloads-info').html('There are no downloads for this product') ;
var productAttribs = this.config.attributesTable;
if (productId && this.config.childProducts[productId].attributesTable) {
productAttribs = this.config.childProducts[productId].attributesTable ;
}
jQuery('.attribs-info').html(productAttribs) ;
decorateTable('product-attribute-specs-table') ;
if (productId && this.config.childProducts[productId].isNew) {
jQuery('.product-image .new-label').show() ;
} else {
jQuery('.product-image .new-label').hide() ;
}
if (productId && this.config.childProducts[productId].isOnSale) {
jQuery('.product-image .sale-label').show() ;
} else {
jQuery('.product-image .sale-label').hide() ;
}
if (productId) jQuery('input[name="pid"]').val(productId) ;
};
Product.Config.prototype.updateProductAvailability = function(productId) {
var stockInfo = this.config.stockInfo;
var is_in_stock = false;
var stockLabel = '';
if (productId && stockInfo[productId]["stockLabel"]) {
stockLabel = stockInfo[productId]["stockLabel"];
stockQty = stockInfo[productId]["stockQty"];
is_in_stock = stockInfo[productId]["is_in_stock"];
}
$$('#product_addtocart_form p.availability span').each(function(el) {
if(is_in_stock) {
$$('#product_addtocart_form p.availability').each(function(es) {
es.removeClassName('availability out-of-stock');
es.addClassName('availability in-stock');
});
el.innerHTML = /*stockQty + ' ' + */stockLabel;
} else {
$$('#product_addtocart_form p.availability').each(function(ef) {
ef.removeClassName('availability in-stock');
ef.addClassName('availability out-of-stock');
});
el.innerHTML = stockLabel;
}
});
};
Product.Config.prototype.updateProductShortDescription = function(productId) {
var shortDescription = this.config.shortDescription;
if (productId && this.config.shortDescriptions[productId].shortDescription) {
shortDescription = this.config.shortDescriptions[productId].shortDescription;
}
$$('#product_addtocart_form div.short-description div.std').each(function(el) {
el.innerHTML = shortDescription;
});
};
Product.Config.prototype.updateProductDescription = function(productId) {
var description = this.config.description;
if (productId && this.config.Descriptions[productId].Description) {
description = this.config.Descriptions[productId].Description;
}
$$('#product_tabs_description_tabbed_contents div.std').each(function(el) {
el.innerHTML = description;
});
};
Product.Config.prototype.updateProductAttributes = function(productId) {
var productAttributes = this.config.productAttributes;
if (productId && this.config.childProducts[productId].productAttributes) {
productAttributes = this.config.childProducts[productId].productAttributes;
}
//If config product doesn't already have an additional information section,
//it won't be shown for associated product either. It's too hard to work out
//where to place it given that different themes use very different html here
console.log(productAttributes) ;
$$('div.product-collateral div.attribs-info').each(function(el) {
el.innerHTML = productAttributes;
decorateTable('product-attribute-specs-table');
});
};
Product.Config.prototype.showCustomOptionsBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if ($('SCPcustomOptionsDiv')==null) {
return;
}
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 1, to: 0.5 });
if(productId) {
//Uncomment the line below if you want an ajax loader to appear while any custom
//options are being loaded.
//$$('span.scp-please-wait').each(function(el) {el.show()});
//prodForm.getElements().each(function(el) {el.disable()});
new Ajax.Updater('SCPcustomOptionsDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 0.5, to: 1 });
//prodForm.getElements().each(function(el) {el.enable()});
}
});
} else {
$('SCPcustomOptionsDiv').innerHTML = '';
try{window.opConfig = new Product.Options([]);} catch(e){}
}
};
Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
var priceFromLabel = '';
var prodForm = $('product_addtocart_form');
if (!productPriceIsKnown && typeof spConfig != "undefined") {
priceFromLabel = spConfig.config.priceFromLabel;
}
var priceSpanId = 'configurable-price-from-' + this.productId;
var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;
if($(priceSpanId) && $(priceSpanId).select('span.configurable-price-from-label'))
$(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
$(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
}
};
//SCP: Forces the 'next' element to have it's optionLabels reloaded too
Product.Config.prototype.configureElement = function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.reloadOptionLabels(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
};
//SCP: Changed logic to use absolute price ranges rather than price differentials
Product.Config.prototype.reloadOptionLabels = function(element){
var selectedPrice;
var childProducts = this.config.childProducts;
var stockInfo = this.config.stockInfo;
//Don't update elements that have a selected option
if(element.options[element.selectedIndex].config){
return;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice", element.options[i].config.allowedProducts);
var mostExpensivePid = this.getProductIdOfMostExpensiveProductInScope("finalPrice", element.options[i].config.allowedProducts);
var cheapestFinalPrice = childProducts[cheapestPid]["finalPrice"];
var mostExpensiveFinalPrice = childProducts[mostExpensivePid]["finalPrice"];
var stock = '';
if(cheapestPid == mostExpensivePid ){
if(stockInfo[cheapestPid]["stockLabel"] != '') {
stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
if (this.config.showOutOfStock){
if(this.config.disable_out_of_stock_option ) {
if(!stockInfo[cheapestPid]["is_in_stock"] ) {
if(cheapestPid == mostExpensivePid ){
element.options[i].disabled=true;
var stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
}
}
var tierpricing = childProducts[mostExpensivePid]["tierpricing"];
element.options[i].text = this.getOptionLabel(element.options[i].config, cheapestFinalPrice, mostExpensiveFinalPrice, stock , tierpricing);
}
}
};
Product.Config.prototype.showTierPricingBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if(productId) {
new Ajax.Updater('sppTierPricingDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
}
});
} else {
$('sppTierPricingDiv').innerHTML = '';
}
};
//SCP: Changed label formatting to show absolute price ranges rather than price differentials
Product.Config.prototype.getOptionLabel = function(option, lowPrice, highPrice, stock, tierpricing){
var str = option.label;
if(tierpricing > 0 && tierpricing < lowPrice) {
var tierpricinglowestprice = ': As low as (' + this.formatPrice(tierpricing,false) + ')';
} else {
var tierpricinglowestprice = '';
}
if (!this.config.showPriceRangesInOptions) {
return str;
}
if (!this.config.showOutOfStock){
stock = '';
}
lowPrices = this.getTaxPrices(lowPrice);
highPrices = this.getTaxPrices(highPrice);
if (this.config.hideprices) {
if (this.config.showOutOfStock){
return str + ' ' + stock + ' ';
} else {
return str;
}
}
var to = ' ' + this.config.rangeToLabel + ' ';
var separator = ': ( ';
if(lowPrice && highPrice){
if (this.config.showfromprice) {
this.config.priceFromLabel = this.config.priceFromLabel; //'From: ';
}
if (lowPrice != highPrice) {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str+= to + this.formatPrice(highPrices[2], false) + ' (' + this.formatPrice(highPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
} else {
str+= separator + this.formatPrice(lowPrices[0], false);
str+= to + this.formatPrice(highPrices[0], false);
str += " ) ";
}
} else {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
str += stock;
str += tierpricinglowestprice;
} else {
if(tierpricing == 0 ) {
str+= separator + this.formatPrice(lowPrices[0], false);
str += " ) ";
}
str += tierpricinglowestprice;
str += ' ' + stock;
}
}
}
return str;
};
//SCP: Refactored price calculations into separate function
Product.Config.prototype.getTaxPrices = function(price) {
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
return [price, incl, excl];
};
//SCP: Forces price labels to be updated on load
//so that first select shows ranges from the start
document.observe("dom:loaded", function() {
//Really only needs to be the first element that has configureElement set on it,
//rather than all.
if (typeof opConfig != "undefined") {
spConfig.reloadPrice();
}
$('product_addtocart_form').getElements().each(function(el) {
if(el.type == 'select-one') {
if(el.options && (el.options.length > 1)) {
el.options[0].selected = true;
spConfig.reloadOptionLabels(el);
}
}
});
});
Thank you
The version 1.5.11 is not compatible w/ Magento 1.9 according to the extension version on Magento connect. Please obtain the newest version of the extension and/or ask the creator to give you support. As far as I can see 1.9 support is support with 1.11.6, released 11th March 2015. The infos on their homepage and Magento connect are different - not good. On the homepage it says Works with Magento 1.9.0.X . tested 15 May 2014.

Hash key access error

I'm having this weird error while accessing the key evenimente of my object. Any ideas why?
It clearly is available but I cannot access it via .(dot)
EDIT: Sorry, here is the code
var isPresent = function(entry) {
var evenimente = entry.evenimente;
var elem = $("#" + entry.nume + "-" + entry.prenume);
for(var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if(eveniment.eveniment_id == eventId && eveniment.user_id == entry.id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}
I get entry via ajax from the server
Looks like your entry is an array (see the [ and ] in your console).
So, you should be able to access the evenimente field this way:
var ev = entry[0].evenimente
The updated code would look like this:
var isPresent = function (entry) {
var evenimente = entry[0].evenimente;
var elem = $("#" + entry[0].nume + "-" + entry[0].prenume);
for (var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if (eveniment.eveniment_id == eventId && eveniment.user_id == entry[0].id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}
Also, for convenience, you could just override the entry value like below:
var isPresent = function (entry) {
entry = entry[0];
if (!entry) {
throw new Error("No available entry.");
}
var evenimente = entry.evenimente;
var elem = $("#" + entry.nume + "-" + entry.prenume);
for (var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if (eveniment.eveniment_id == eventId && eveniment.user_id == entry.id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}

add an object or edit if exist (indexeddb)

I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
var elements = document.getElementsByClassName('layers');
for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
index = object.index("by_Name");
request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));
request.onsuccess = function (e) {
var result = e.target.result;
if (result === undefined) {
var resultPut = object.put({
Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
Count: 1,
Type: String(elements[i].getAttribute("src").split("/")[4])
});
resultPut.onerror = function (e) {
alert(resultPut.error.name + '\n\n' + resultPut.error.message);
};
} else {
result.Count++;
var requestUpdate = object.put(result);
requestUpdate.onerror = function (event) {
alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
};
}
}(event);
}
}
alert("Finish");
})
The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
(function(myElement) {
if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
...
}
})(elements[i]);
}

XML Javascript undefined error in ie9

I have a 'jargon buster' on my site that uses an xml file to load an A-Z of words which when clicked display a brief short explanation of each word. This works fine in all browsers bar the latest ie's which i get an 'undefined' error with. The jscript im using is below
Jargon = {
xmlfile: 'http://www.mysite.com/jargon.xml',
xml: null,
wordHolder: 'words',
defHolder: 'definition',
idprefix: 'jargon_',
selected: null,
init: function () {
var con = Jargon.xhcon();
Jargon.wordHolder = $(Jargon.wordHolder);
Jargon.defHolder = $(Jargon.defHolder);
if (!con || !Jargon.wordHolder || !Jargon.defHolder) {
return;
}
function conComplete(oXML) {
Jargon.xml = oXML.responseXML;
//Jargon.showWords('a');
}
con.connect(Jargon.xmlfile, 'GET', Math.random(), conComplete);
},
showWords: function (c) {
if (Jargon.selected) {
Jargon.selected.className = '';
}
var words = Jargon.getWords(c);
while (Jargon.wordHolder.childNodes.length > 0) {
Jargon.wordHolder.removeChild(Jargon.wordHolder.childNodes[0]);
}
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
for (var i = 0; i < words.length; i++) {
var o = document.createElement('a');
o.href = 'javascript:Jargon.showDef(\'' + words[i].id + '\');';
o.id = Jargon.idprefix + words[i].id;
//o.onclick = Jargon.showDef;
o.appendChild($t(words[i].name));
Jargon.wordHolder.appendChild(o);
Jargon.wordHolder.appendChild(document.createElement('br'));
}
if (!words.length) {
var o = document.createElement('p');
var s = 'There are no words for the letter ' + c.toUpperCase();
Jargon.wordHolder.appendChild(o.appendChild($t(s)));
}
},
showDef: function (id) {
var o = $(Jargon.idprefix + id);
if (Jargon.selected) {
Jargon.selected.className = '';
}
if (o) {
o.className = 'selected';
Jargon.selected = o;
}
var defobjs = Jargon.getDef(id);
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
var heading = document.createElement('span');
heading.className = "jargtitle";
heading.appendChild(document.createTextNode(defobjs[1][0].textContent));
Jargon.defHolder.appendChild(heading);
var definition = document.createElement('span');
definition.className = "jargdefinition";
definition.appendChild(document.createTextNode(defobjs[0][0].textContent));
Jargon.defHolder.appendChild(definition);
},
getWords: function(c) {
var x = Jargon.xml;
var letters = x.getElementsByTagName('letter');
var oLetter = null;
for (var i = 0; i < letters.length; i++) {
if (letters[i].getAttribute('id') == c) {
oLetter = letters[i];
break;
}
}
if (!oLetter) {
return [];
}
var words = [];
for (i = 0; i < oLetter.childNodes.length; i++) {
var oJargon = oLetter.childNodes[i];
if (oJargon.nodeName == 'jargon') {
var s = Jargon.getName(oJargon);
words[words.length] = {
id: oLetter.childNodes[i].getAttribute('id'),
name: s
};
}
}
return words;
},
getDef: function (id) {
var x = Jargon.xml;
var j = null;
var temp = new Array(2);
var jargons = x.getElementsByTagName('jargon');
for (var i = 0; i < jargons.length; i++) {
if (jargons[i].getAttribute('id') == id) {
j = jargons[i];
break;
}
}
if (!j) {
return [];
}
//return [];
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'name') {
temp[1] = j.childNodes[i].childNodes;
}
}
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'desc') {
temp[0] = j.childNodes[i].childNodes;
}
}
//return [];
return temp;
},
cloneNode: function (oldNode, deep) {
deep = (deep) ? true : false;
// a replacement to the normal dom clone node
// this will copy xml nodes to html nodes
// which can then be inserted into the document
// scope in all browsers
// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
var newNode = null;
if (oldNode.nodeType == '3') {
// textnode
newNode = $t(oldNode.nodeValue);
}
else if (oldNode.nodeType == '1') {
// element node
newNode = document.createElement(oldNode.nodeName);
if (deep) {
for (var i = 0; i < oldNode.childNodes.length; i++) {
newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
}
}
}
return newNode;
},
getName: function (oJargon) {
for (var i = 0; i < oJargon.childNodes.length; i++) {
if (oJargon.childNodes[i].nodeName == 'name') {
var oName = oJargon.childNodes[i];
var s = '';
for (var j = 0; j < oName.childNodes.length; j++) {
if (oName.childNodes[j].nodeType == 3) {
// text node
s += oName.childNodes[j].nodeValue;
}
}
return s;
}
}
return '';
},
xhcon: function () {
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) {
return null;
}
this.connect = function(sURL, sMethod, sVars, fnDone) {
if (!xmlhttp) {
return false;
}
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET") {
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else {
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && !bComplete) {
bComplete = true;
fnDone(xmlhttp);
}
};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
}
In terms of how im calling the jscript im using <li>a</li>
which loads a list of all items that begin with f then when i click one of items from that list say "Fiduciary" it triggers javascript:Jargon.showDef('f1'); which in turns loads the and into a definition div
however in ie9 it displays "undefined" . It works in all other browers
Example of the XML below:
<letter id="f"> -<jargon id="f1"> <name>Fiduciary</name> <desc>in a position of trust. This includes people such as trustees looking after trust assets for the beneficiaries and company directors running a company for the shareholders' benefit.</desc> </jargon> -<jargon id="f2"> <name>Forfeiture</name> <desc>the loss of possession of a property because the tenancy conditions have not been met by the tenant.</desc> </jargon> -<jargon id="f3"> <name>Freehold</name> <desc>describing land that only the owner has any rights over.</desc> </jargon> -<jargon id="f4"> <name>Free of encumbrances</name> <desc>no one else having any rights over something. When property is owned by someone and nobody else has any rights over it, it is owned free of encumbrances.</desc> </jargon> </letter>

Categories

Resources