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.
Related
My google reviews are not being fetched. I've tried the code below but it doesn't work. I've created an api and put this in along with my placeid in all of the code below but nothing displays.
I followed multiple tutorials which all give basically the same code. I'm not sure why this isn't working.
Does anyone know what I'm doing wrong or have any suggestions on how to implement this in an easier way.
html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/google-places.js "></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=[API_KEY]"></script>
<script>
jQuery(document).ready(function() {
$("#google-reviews").googlePlaces({
placeId: '[PLACES_ID]',
render: ['reviews'],
min_rating: 3,
max_rows: 0
});
});
</script>
</head>
<body>
<div id="google-reviews"></div>
</body>
javascript:
/* https://github.com/peledies/google-places */
(function($) {
var namespace = 'googlePlaces';
$.googlePlaces = function(element, options) {
var defaults = {
placeId: 'PLACEID' // placeId provided by google api documentation
, render: ['reviews']
, min_rating: 3
, max_rows: 0
, map_plug_id: 'map-plug'
, rotateTime: false
, shorten_names: true
, schema:{
displayElement: '#schema'
, type: 'Store'
, beforeText: 'Google Users Have Rated'
, middleText: 'based on'
, afterText: 'ratings and reviews'
, image: null
, priceRange: null
}
, address:{
displayElement: "#google-address"
}
, phone:{
displayElement: "#google-phone"
}
, staticMap:{
displayElement: "#google-static-map"
, width: 512
, height: 512
, zoom: 17
, type: "roadmap"
}
, hours:{
displayElement: "#google-hours"
}
};
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
plugin.settings.schema = $.extend({}, defaults.schema, options.schema);
$element.html("<div id='" + plugin.settings.map_plug_id + "'></div>"); // create a plug for google to load data into
initialize_place(function(place){
plugin.place_data = place;
// Trigger event before render
$element.trigger('beforeRender.' + namespace);
if(plugin.settings.render.indexOf('rating') > -1){
renderRating(plugin.place_data.rating);
}
// render specified sections
if(plugin.settings.render.indexOf('reviews') > -1){
renderReviews(plugin.place_data.reviews);
if(!!plugin.settings.rotateTime) {
initRotation();
}
}
if(plugin.settings.render.indexOf('address') > -1){
renderAddress(
capture_element(plugin.settings.address.displayElement)
, plugin.place_data.adr_address
);
}
if(plugin.settings.render.indexOf('phone') > -1){
renderPhone(
capture_element(plugin.settings.phone.displayElement)
, plugin.place_data.formatted_phone_number
);
}
if(plugin.settings.render.indexOf('staticMap') > -1){
renderStaticMap(
capture_element(plugin.settings.staticMap.displayElement)
, plugin.place_data.formatted_address
);
}
if(plugin.settings.render.indexOf('hours') > -1){
renderHours(
capture_element(plugin.settings.hours.displayElement)
, plugin.place_data.opening_hours
);
}
// render schema markup
addSchemaMarkup(
capture_element(plugin.settings.schema.displayElement)
, plugin.place_data
);
// Trigger event after render
$element.trigger('afterRender.' + namespace);
});
}
var capture_element = function(element){
if(element instanceof jQuery){
return element;
}else if(typeof element == 'string'){
try{
var ele = $(element);
if( ele.length ){
return ele;
}else{
throw 'Element [' + element + '] couldnt be found in the DOM. Skipping '+element+' markup generation.';
}
}catch(e){
console.warn(e);
}
}
}
var initialize_place = function(c){
var map = new google.maps.Map(document.getElementById(plugin.settings.map_plug_id));
var request = {
placeId: plugin.settings.placeId
};
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
c(place);
}
});
}
var sort_by_date = function(ray) {
ray.sort(function(a, b){
var keyA = new Date(a.time),
keyB = new Date(b.time);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
return ray;
}
var filter_minimum_rating = function(reviews){
for (var i = reviews.length -1; i >= 0; i--) {
if(reviews[i].rating < plugin.settings.min_rating){
reviews.splice(i,1);
}
}
return reviews;
}
var renderRating = function(rating){
var html = "";
var star = renderAverageStars(rating);
html = "<div class='average-rating'><h4>"+star+"</h4></div>";
$element.append(html);
}
var shorten_name = function(name) {
if (name.split(" ").length > 1) {
var xname = "";
xname = name.split(" ");
return xname[0] + " " + xname[1][0] + ".";
}
}
var renderReviews = function(reviews){
reviews = sort_by_date(reviews);
reviews = filter_minimum_rating(reviews);
var html = "";
var row_count = (plugin.settings.max_rows > 0)? plugin.settings.max_rows - 1 : reviews.length - 1;
// make sure the row_count is not greater than available records
row_count = (row_count > reviews.length-1)? reviews.length -1 : row_count;
for (var i = row_count; i >= 0; i--) {
var stars = renderStars(reviews[i].rating);
var date = convertTime(reviews[i].time);
if(plugin.settings.shorten_names == true) {
var name = shorten_name(reviews[i].author_name);
} else {
var name = reviews[i].author_name + "</span><span class='review-sep'>, </span>";
};
html = html+"<div class='review-item'><div class='review-meta'><span class='review-author'>"+name+"<span class='review-date'>"+date+"</span></div>"+stars+"<p class='review-text'>"+reviews[i].text+"</p></div>"
};
$element.append(html);
}
var renderHours = function(element, data){
if(element instanceof jQuery){
var html = "<ul>";
data.weekday_text.forEach(function(day){
html += "<li>"+day+"</li>";
});
html += "</ul>";
element.append(html);
}
}
var renderStaticMap = function(element, data){
if(element instanceof jQuery){
var map = plugin.settings.staticMap;
element.append(
"<img src='https://maps.googleapis.com/maps/api/staticmap"+
"?size="+map.width+"x"+map.height+
"&zoom="+map.zoom+
"&maptype="+map.type+
"&markers=size:large%7Ccolor:red%7C"+data+"'>"+
"</img>");
}
}
var renderAddress = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var renderPhone = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var initRotation = function() {
var $reviewEls = $element.children('.review-item');
var currentIdx = $reviewEls.length > 0 ? 0 : false;
$reviewEls.hide();
if(currentIdx !== false) {
$($reviewEls[currentIdx]).show();
setInterval(function(){
if(++currentIdx >= $reviewEls.length) {
currentIdx = 0;
}
$reviewEls.hide();
$($reviewEls[currentIdx]).fadeIn('slow');
}, plugin.settings.rotateTime);
}
}
var renderStars = function(rating){
var stars = "<div class='review-stars'><ul>";
// fill in gold stars
for (var i = 0; i < rating; i++) {
stars = stars+"<li><i class='star'></i></li>";
};
// fill in empty stars
if(rating < 5){
for (var i = 0; i < (5 - rating); i++) {
stars = stars+"<li><i class='star inactive'></i></li>";
};
}
stars = stars+"</ul></div>";
return stars;
}
var renderAverageStars = function(rating){
var stars = "<div class='review-stars'><ul><li><i>"+rating+" </i></li>";
var activeStars = parseInt(rating);
var inactiveStars = 5 - activeStars;
var width = (rating - activeStars) * 100 + '%';
// fill in gold stars
for (var i = 0; i < activeStars; i++) {
stars += "<li><i class='star'></i></li>";
};
// fill in empty stars
if(inactiveStars > 0){
for (var i = 0; i < inactiveStars; i++) {
if (i === 0) {
stars += "<li style='position: relative;'><i class='star inactive'></i><i class='star' style='position: absolute;top: 0;left: 0;overflow: hidden;width: "+width+"'></i></li>";
} else {
stars += "<li><i class='star inactive'></i></li>";
}
};
}
stars += "</ul></div>";
return stars;
}
var convertTime = function(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var time = months[a.getMonth()] + ' ' + a.getDate() + ', ' + a.getFullYear();
return time;
}
var addSchemaMarkup = function(element, placeData) {
if(element instanceof jQuery){
var schema = plugin.settings.schema;
var schemaMarkup = '<span itemscope="" itemtype="http://schema.org/' + schema.type + '">';
if(schema.image !== null) {
schemaMarkup += generateSchemaItemMarkup('image', schema.image);
} else {
console.warn('Image is required for some schema types. Visit https://search.google.com/structured-data/testing-tool to test your schema output.');
}
if(schema.priceRange !== null) {
schemaMarkup += generateSchemaItemMarkup('priceRange', schema.priceRange);
}
schemaMarkup += generateSchemaItemMarkup('url', location.origin);
schemaMarkup += generateSchemaItemMarkup('telephone', plugin.place_data.formatted_phone_number );
schemaMarkup += generateSchemaAddressMarkup();
schemaMarkup += generateSchemaRatingMarkup(placeData, schema);
schemaMarkup += '</span>';
element.append(schemaMarkup);
}
}
var generateSchemaAddressMarkup = function() {
var $address = $('<div />', {
itemprop: "address"
, itemscope: ''
, itemtype: "http://schema.org/PostalAddress"
}).css('display', 'none');
$address.append(plugin.place_data.adr_address);
$address.children('.street-address').attr('itemprop', 'streetAddress');
$address.children('.locality').attr('itemprop', 'addressLocality');
$address.children('.region').attr('itemprop', 'addressRegion');
$address.children('.postal-code').attr('itemprop', 'postalCode');
$address.children('.country-name').attr('itemprop', 'addressCountry');
return $address[0].outerHTML;
}
var generateSchemaRatingMarkup = function(placeData, schema) {
var reviews = placeData.reviews;
var lastIndex = reviews.length - 1;
var reviewPointTotal = 0;
for (var i = lastIndex; i >= 0; i--) {
reviewPointTotal += reviews[i].rating;
};
var averageReview = reviewPointTotal / ( reviews.length );
return schema.beforeText + ' <span itemprop="name">' + placeData.name + '</span> '
+ '<span itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">'
+ '<span itemprop="ratingValue">' + averageReview.toFixed(2) + '</span>/<span itemprop="bestRating">5</span> '
+ schema.middleText + ' <span itemprop="ratingCount">' + reviews.length + '</span> '
+ schema.afterText
+ '</span>'
}
var generateSchemaItemMarkup = function(name, value) {
return '<meta itemprop="' + name + '" content="' + value + '">'
}
plugin.init();
}
$.fn.googlePlaces = function(options) {
return this.each(function() {
if (undefined == $(this).data(namespace)) {
var plugin = new $.googlePlaces(this, options);
$(this).data(namespace, plugin);
}
});
}
})(jQuery);
I've also tried just this instead of everything above but still nothing displays.
html:
<div id="google-reviews"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://tutorialswebsite.com/cdn/google_places.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&signed_in=true&libraries=places"></script>
<script>
jQuery(document).ready(function( $ ) {
$("#google-reviews").googlePlaces({
placeId: 'PLACEID' //Find placeID #: https://developers.google.com/places/place-id
, render: ['reviews']
, min_rating:3
, max_rows:5
,rotateTime: false
, shorten_names: true
});
});
</script>
I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.
This is an extension of the following question. I can't use it because PropertiesService and ScriptApp is not supported in Adwords and I didn't find anything relevant so far on the question adapted to Adwords.
I have an Adwords script that constantly gets the error Exceeded maximum execution time. For an MCC accounts, I think the maximum time execution is 30 minutes. Does anyone know if there is a way to extend this time limit? Or perhaps is there a way to call the Adwords script again and it picks up from where it left off? Queuing? Could I use an MCCScript with Google-Apps-Script?
Here is what I have done so far ...
function timeDrivenTrigger(myFunct) {
var REASONABLE_TIME_TO_WAIT = 4*6000;
var MAX_RUNNING_TIME = 1*6000;
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1sYQ__CM33oL2OLzbScQEdcQ6LvDxJCohP024vdSGfSI/edit#gid=0');
var sheet = ss.getSheets()[0];
var cell = sheet.getRange('A1');
var startTime= (new Date()).getTime();
myFunct;
var startRow= cell.getValue() || 1;
for(var ii = startRow; ii <= 10000; ii++) {
var currTime = (new Date()).getTime();
if(currTime - startTime >= MAX_RUNNING_TIME) {
cell.setValue(ii);
ScriptApp.newTrigger("runMe")
.timeBased()
.at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
.create();
break;
}
}
}
UPDATE WITH PARALLEL EXECUTION
Here is my whole code ...
//Your build Google-Spreadsheet
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1k4o_8O_11OvhZRergefWKgXQ8_XxIs7D31-NV9Ove-o/edit#gid=749396300";
//Fetch and convert data in a JSON structure
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName('Campaigns');
var data = sheet.getRange("A:C").getValues();
var accountList = accountsListing(data);
accountList= accountList.map(function (el) {
return el.trim();
});
function main() {
accountIdList = [];
accountItr = MccApp.accounts().get();
while(accountItr.hasNext()) {
account = accountItr.next();
if (accountList.indexOf(account.getName()) > -1) {
accountIdList.push(account.getCustomerId())
}
}
if(accountList.length > 0) {
var accountSelector = MccApp.accounts()
.withIds(accountIdList)
.withLimit(40);
accountSelector.executeInParallel('adjustCPCmax');
}
}
String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};
function isBlank(line) {
return line[0].trim() === '' && line[1].trim() === '';
}
function parseData(data) {
const output = {};
var currentGroupName = '';
data.forEach(function(line, index){
if (isBlank(line) || index === 0){
return;
}
if (line[0].trim().length > 1) {
currentGroupName = line[0].trim();
}
output[currentGroupName] = output[currentGroupName] || {};
output[currentGroupName][line[1]] = line[2];
});
return output;
}
function accountsListing(data) {
function isBlank(line){
return line[0].trim() === '';
}
const output = [];
data.forEach(function(line, index) {
if (isBlank(line) || index === 0) {
return;
}
output.push(line[0])
});
return output
}
function parseKeyword(keyword, keywordId, maxCPC) {
Logger.log('THE NAME OF THE KEYWORDID IS ' + keywordId + '\n')
var report = AdWordsApp.report(
'SELECT Id, Criteria, CampaignName, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE ' +
'Id = ' + keywordId);
var rows = report.rows();
while(rows.hasNext()) {
var row = rows.next();
var keywordIdReport = row['Id'];
var keywordNameReport = row['Criteria'];
var campaignName = row['CampaignName'];
var cpcBid = row['CpcBid'];
var firstPageCpc = row['FirstPageCpc'];
var firstPositionCpc = row['FirstPositionCpc'];
var topOfPageCpc = row['TopOfPageCpc'];
Logger.log('INFO')
Logger.log(keyword.getText())
Logger.log(keywordId)
Logger.log(keywordNameReport)
Logger.log(keywordIdReport + '\n')
if (keywordId === keywordIdReport) {
if (firstPositionCpc && (firstPositionCpc > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
var newCPC = firstPageCpc;
} else {
var newCPC = minCPC;
}
Logger.log('KeywordIdReport :' + keywordIdReport)
Logger.log('campaignName :' + campaignName)
Logger.log('CPCbid :' + cpcBid)
Logger.log('firstPositionCpc : ' + firstPositionCpc)
Logger.log('topOfPageCpc : ' + topOfPageCpc)
Logger.log('firstPageCpc : ' + firstPageCpc)
Logger.log('NewCPC : ' + newCPC + '\n')
keyword.bidding().setCpc(newCPC)
break;
}
}
}
function getMaxCPC(account, campaign) {
var cleanData= parseData(data);
//Formatting account and campaign
var account = '{}'.format(account.getName())
var campaign = '{}'.format(campaign.getName())
Logger.log('Account :' + account)
Logger.log('Campaign :' + campaign + '\n')
return cleanData[account][campaign];
}
function adjustCPCmax() {
//min CPC
var minCPC = 0.50;
var account = AdWordsApp.currentAccount();
Logger.log('=================================' + account.getName() + "=======================================")
var campaignIterator = AdWordsApp.campaigns().get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
try {
var maxCPC = getMaxCPC(account, campaign)
}
catch(e) {
}
if (maxCPC) {
Logger.log('The entrence worked with max CPC : ' + maxCPC + '\n')
keywordIterator = campaign.keywords().get();
var startTime= (new Date()).getTime();
while (keywordIterator.hasNext()) {
var keyword= keywordIterator.next()
var keywordId = Number(keyword.getId()).toPrecision()
parseKeyword(keyword, keywordId, maxCPC);
}
}
}
}
Be aware that this code will work in the MCC script environment. It could work for any account from a Google spreadsheet.
P.S. This following question gave me a good idea how to process, but I want to know your suggestions.
Here we added the logic to display which ranks are duplicated but I also want to display exactly which rank is duplicated. Ranks are from 0 to 18.
function validate(sdd_ejrp_form)
{
var duplicateRanksDetected = false;
var validate_rank_str = ",";
jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function (index)
{ var jqThis = jq(this);
var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
jqThis.find("\[data-dom-id=proficiency-level\]").each(function (index2)
{
var btn = jq(this);
if (btn.hasClass("active"))
{
if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1)
{
duplicateRanksDetected = true;
return false;
} else
{
validate_rank_str += prof_lvl_rank + ",";
}
}
});
});
if (duplicateRanksDetected == true)
{
// here I want to display exactly which rank is duplicated
alert("Duplicate ranks detected!");
return false;
}
}
}
It's easy as 3 modifications:
function validate(sdd_ejrp_form) {
var duplicateRanksDetected = []; //create an array here
var validate_rank_str = ",";
jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function(index) {
var jqThis = jq(this);
var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
jqThis.find("\[data-dom-id=proficiency-level\]").each(function(index2) {
var btn = jq(this);
if (btn.hasClass("active")) {
if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1) {
duplicateRanksDetected.push(prof_lvl_rank); // fill the array here
return false;
} else {
validate_rank_str += prof_lvl_rank + ",";
}
}
});
});
if (duplicateRanksDetected.length > 0) {
// here I want to display exactly which rank is duplicated
alert(
"Duplicate ranks detected: " +
duplicateRanksDetected.join(', ') // display the result here
);
return false;
}
}
I have a bid-to-position script that targets keywords that have a label associated with them. The label contains the desired position and the script adjusts the keyword's bid in order to reach that position. Right now the script targets any keyword with the label. I'm trying to edit the script so it will look for labeled keywords in campaigns that I choose. I tried adding .withCondition(CampaignName = ' My Campaign Name'") to the labelIterator variable but had no luck. Can anyone point me in the right direction?
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.2
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 5.00;
// Bids will not be increased past this maximum.
var minBid = 0.10;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 1.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = false;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.2;
var bidDecreaseProportion = 0.4;
var targetPositionTolerance = 0.2;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
var labels = row["Labels"].toLowerCase().split("; ")
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
try {
updateKeywords();
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var content = resultsString();
file.setContent(content);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords() {
var keywordIterator = AdWordsApp.keywords()
.withIds(uniqueIds.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
so CampaignName isn't a valid with condition for the label selector. What you need to do instead is have a Campaign Selector in a while look before you come to your Label selector, which then feeds from the campaign iteration. I've done a quick and dirty example below, but of course, you'd have to take a look to see if doing this will require other changes later on (or earlier on) in your code.
var labelIds = [];
var campaignIterator = AdWordsApp.campaigns()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.get()
while (campaignIterator.hasNext())
{
var campaign = campaignIterator.next()
var labelIterator = campaign.labels()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
}
var labelIterator = AdWordsApp.labels()