I have a situation here. My company has a webpage which we use for ticket creation. The user gets the email and he has to create a ticket based on the info in the email. I tried to automate this process however got stuck at uploading the attachment.
When the user click on the attach button, a new pop up opens and my macro looses the control over the pop up.
So currently what am doing is,
Save the email - which needs to be attached.
Copy the path to clip board using a function
run a vb script to paste and enter using send keys with 5 seconds delay
click on the attach button.
So before the macro clicks the attach button, a VBS runs behind to paste and hit enter. So by the time the pop up opens VBS starts and closes the pop up.
I was checking to run the attach function within VB script so that I dont have to click on attach button. But I am not able to reach anywhere. anyone help?
The below are the functions available in the webpage. I dont know which one to run and how.
<script eval="true">/**
* Validate the attachments to see if at least
* one file is attached. Otherwise, show an alert.
*
* #returns {Boolean}
*/
function validateAttachment() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (fileFields[i] && fileFields[i].value != "") {
setAttachButton(""); //disable
$('please_wait').style.display = "";
return true;
}
}
alert("Choose a file to attach");
return false;
}
/**
* Does the first attachment input field have a value?
* If not, use the grey button and change type of cursor.
* #param value
*/
function setDeleteButton(value) {
var field = $$('.attachmentRow')[0];
var text = field.select('input')[0];
var deleteButton = field.select('a.attachfile-delete img')[0];
if (!text.getValue().empty()) {
deleteButton.setAttribute('src', 'images/icons/kb_no.gif');
deleteButton.up().style.cursor = 'pointer';
} else {
deleteButton.setAttribute('src', 'images/icons/kb_no_disabled.gif');
deleteButton.up().style.cursor = 'default';
}
}
/**
* If the value passed in is an empty string,
* set the button to disabled state, otherwise
* enabled.
*
* #param value
*/
function setAttachButton(value) {
var attachButton = $("attachButton");
if (value == "")
attachButton.disabled = "true";
else
attachButton.disabled = "";
}
/**
* This controls the remove button for all attachments.
* If there are attachments in the list enable the button.
* Else keep disabled.
*
* #param e
*/
function setRemoveButton(e) {
var removeButton = gel("removeButton");
var deletedSysIdsElement = gel("deleted_sys_ids");
var deletedSysIds = new Array();
var deletedString = deletedSysIdsElement.value;
if (deletedString)
deletedSysIds = deletedString.split(";");
var thisId = e.name.substring(7);
if (e.checked) {
removeButton.disabled = "";
deletedSysIds.push(thisId);
} else {
var index = deletedSysIds.indexOf(thisId);
deletedSysIds.splice(index, 1);
// are there any left checked?
var inputs = document.getElementsByTagName("input");
var nonechecked = true;
var i = 0;
while(i < inputs.length && nonechecked) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
if (inputs[i].checked)
nonechecked = false;
i++;
}
if (nonechecked) {
removeButton.disabled = "true";
}
}
deletedSysIds = deletedSysIds.join(";");
deletedSysIdsElement.value = deletedSysIds;
}
function startRemoveAttachments() {
var removeButton = gel("removeButton");
removeButton.disabled = true;
gel('please_wait').style.display = "";
var thisUrl = gel("sysparm_this_url");
thisUrl.value = "attachment_deleted.do?sysparm_domain_restore=false&sysparm_nostack=yes&sysparm_deleted=" + gel("deleted_sys_ids").value;
return true;
}
/**
* Clear and Remove the attachment field that is
* passed in.
*
* #param field_id
*/
function clearAttachmentField(field) {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
fileFields[0].setAttribute('data-position', 'first');
if (fileFields.size() > 1 && (field.readAttribute('data-position') != "first")) {
//check if field you are removing has a 3rd column (does it have an attach button?)
var needToAttachButton;
var attachButton = field.select('td')[2];
if (attachButton)
needToAttachButton = true;
//remove the field
field.remove();
//if you removed a field with a third column, add an attachbutton onto the new "first" field.
if (attachButton) {
var attachButton = new Element('input', {
"type": "submit",
"id": "attachButton",
"disabled": "true",
"value": "Attach" });
var td = new Element('td', {align: 'right'}).update(attachButton);
Element.extend(td);
form.select('.attachmentRow').first().select('td')[1].insert({'after': td});
}
}
else
clearFileField(field.select('td').first().select('input').first());
checkAndSetAttachButton();
}
/**
* Check all attachment input fields. If there is not attachment
* currently, disable the attachment button, else enable it.
*
* #returns
*/
function checkAndSetAttachButton() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
var validFileCount = 0;
for (var i = 0; i < fileFields.size(); i++) {
var field = fileFields[i].select('td').first().select('input').first();
if (field.getValue() != "") {
if (window.File && window.FileReader && window.FileList)
validFileCount += validateSizeandExt(field);
else
validFileCount += 1;
}
}
if (validFileCount == 0)
setAttachButton("");
else
setAttachButton("true");
}
function validateSizeandExt(field) {
var form = $('sys_attachment');
var maxSize = (form.max_size && form.max_size.value) ? form.max_size.value : 0;
var fileTypes = (form.file_types && form.file_types.value) ? form.file_types.value : "";
var files = field.files;
var allowedSize = maxSize * 1048576;
var warningString = "";
var checkJEXL = true;
for (var i = 0; i < files.length; i++) {
if (checkJEXL && isJEXLExpression(files[i].name)) {
warningString += files[i].name + " is an invalid file name.\n";
}
if (files[i].size > allowedSize && allowedSize != 0)
warningString += files[i].name + " is " + getDisplaySize(files[i].size) + ". The maximum file size is " + getDisplaySize(allowedSize) + ".\n";
if (!isValidFileType(files[i], fileTypes))
warningString += files[i].name + " has a prohibited file extension." + "\n";
}
if (warningString != "") {
alert(warningString);
clearFileField(field);
return 0;
}
return 1;
}
function isJEXLExpression(fileName) {
var phaseOneOpening = fileName.indexOf("$" + "{");
var phaseTwoOpening = fileName.indexOf("$" + "[");
if (phaseOneOpening != -1 || phaseTwoOpening != -1) {
return true;
}
return false;
}
function getDisplaySize(sizeInBytes) {
var kilobytes = Math.round(sizeInBytes / 1024);
if (kilobytes < 1)
kilobytes = 1;
var reportSize = kilobytes + "K";
if (kilobytes > 1024)
reportSize = Math.round(kilobytes / 1024) + "MB";
return reportSize;
}
function isValidFileType(file, types) {
var extensions = types || "";
if (extensions != "") {
extensions.toLowerCase();
extensions = extensions.split(",");
var periodIndex = file.name.lastIndexOf(".");
var extension = file.name.substring(periodIndex+1).toLowerCase();
if (extensions.indexOf(extension) == -1)
return false;
}
return true;
}
/**
* Clear a given field's contents.
*
* #param field
* the field element.
*/
function clearFileField(field) {
$(field).clear();
$(field).parentNode.innerHTML = $(field).parentNode.innerHTML;
checkAndSetAttachButton();
}
/**
* If the attachments are uploaded, clear any extra attachment input fields so
* they do not take up as much screen space. Additionally, clear the first field
* and keep it showing.
*/
function clearAttachmentFields() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (i == 0)
clearFileField(fileFields[0].select('td').first().select('input').first());
if (i > 0)
fileFields[i].remove();
}
checkAndSetAttachButton();
setDeleteButton();
}
// this get called after an attachment is uploaded to update the display
function refreshAttachments(id, fileName, canDelete, createdBy, createdOn, contentType, encryption, iconPath) {
refreshLiveFeedAttachments(id, fileName, contentType, iconPath);
var encryptCheck = gel("encrypt_checkbox");
if (encryptCheck) {
encryptCheck.checked = false;
$('sysparm_encryption_context').value = "";
}
gel("please_wait").style.display = "none";
// if we didn't get an id, we could not read the attachment due to business rules so we're done
if (typeof id == "undefined")
return;
var noAttachments = gel("no_attachments");
if (noAttachments.style.display == "block")
noAttachments.style.display = "none";
// add the new upload to the display
var table = gel("attachment_table_body");
var tr = cel("tr");
var td = cel("td");
td.style.whiteSpace = "nowrap";
td.colspan = "2";
if (canDelete=="true") {
var input = cel("input");
var checkId = "sys_id_" + id;
input.name = checkId;
input.id = checkId;
input.type = "checkbox";
input.onclick = function() {setRemoveButton(gel(checkId));};
td.appendChild(input);
gel("delete_button_span").style.display = "inline";
var text = document.createTextNode(" ");
td.appendChild(text);
input = cel("input");
input.type = "hidden";
input.name = "Name";
input.value = "false";
td.appendChild(input);
}
var attachment_input = cel("input");
attachment_input.className = "attachment_sys_id";
attachment_input.type = "hidden";
attachment_input.id = id;
td.appendChild(attachment_input);
var anchor = cel("a");
anchor.style.marginRight = "4px";
anchor.href = "sys_attachment.do?sys_id=" + id;
anchor.title = "Attached by " + createdBy + " on " + createdOn;
var imgSrc = iconPath;
if (encryption != "") {
anchor.title += ", Encrypted: " + encryption;
imgSrc = "images/icons/attachment_encrypted.gifx";
}
var img = cel("img");
img.src = imgSrc;
img.alt = anchor.title;
anchor.appendChild(img);
var text = $(cel('a'));
getMessage("Download {0}", function(msg) {
text.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
text.href = "sys_attachment.do?sys_id=" + id;
text.onkeydown = function(event){return allowInPlaceEditModification(text, event);};
text.style.marginRight = "5px";
text.style.maxWidth = "75%";
text.style.display = "inline-block";
text.style.overflow = "hidden";
text.style.verticalAlign = "middle";
if ('innerText' in text)
text.innerText = fileName;
else
text.textContent = fileName;
text.setAttribute("data-id", id);
text.inPlaceEdit({
selectOnStart: true,
turnClickEditingOff: true,
onBeforeEdit: function() {
text.lastAriaLabel = text.getAttribute("aria-label");
text.removeAttribute("aria-label");
text.setAttribute("role", "textbox");
},
onEditCancelled: function() {
text.removeAttribute("role");
if (text.lastAriaLabel) {
text.setAttribute("aria-label", text.lastAriaLabel);
}
},
onAfterEdit: function(newName) {
var oldName = this.oldValue;
var ga = new GlideAjax('AttachmentAjax');
ga.addParam('sysparm_type', 'rename');
ga.addParam('sysparm_value', id);
ga.addParam('sysparm_name', newName);
ga.getXML(function(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer !== '0')
alert(new GwtMessage().getMessage("Renaming attachment {0} to new name {1} is not allowed", oldName, newName));
$$('a[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
$$('span[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
/*
This routine updates the attachment in the attachment modal AND the same attachment on the parent form
*/
getMessage(["Download {0}", "View {0}", "Rename {0}"], function(msg) {
var newDownloadText = new GwtMessage().format(msg["Download {0}"], newName);
var newViewText = new GwtMessage().format(msg["View {0}"], newName);
var newRenameText = new GwtMessage().format(msg["Rename {0}"], newName);
console.log(id)
$$('a[data-id="' + id + '"]').each(function(elem){
elem.setAttribute("aria-label", newDownloadText);
})
$$('.view_' + id).each(function(elem){
elem.setAttribute("aria-label", newViewText);
})
$$('.rename_' + id).each(function(elem){
elem.setAttribute("aria-label", newRenameText);
})
})
text.removeAttribute("role");
});
}
});
if (contentType == "text/html")
anchor.target = "_blank";
td.appendChild(anchor);
td.appendChild(text);
var allowRename = gel('ni.show_rename_link').value;
if (allowRename == "true") {
var renameAttachment = $(cel('a'));
renameAttachment.href = "#";
renameAttachment.setAttribute("role", "button");
getMessage("Rename {0}", function(msg) {
renameAttachment.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
renameAttachment.className = 'attachment rename_' + id;
renameAttachment.onclick = function() {
text.beginEdit();
};
renameAttachment.innerHTML = '[rename]';
td.appendChild(renameAttachment);
}
var showView = gel("ni.show_attachment_view").value;
if (showView == "true") {
var blank = document.createTextNode(" ");
tr.appendChild(blank);
var view = cel("a");
view.href = "#";
getMessage("View {0}", function(msg) {
view.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
var newText = document.createTextNode('[view]');
view.appendChild(newText);
view.className = "attachment view_" + id;
if (showPopup == "false")
view.href = "sys_attachment.do?sys_id=" + id + "&view=true";
else
view.onclick = function() {
tearOffAttachment(id)
};
td.appendChild(blank);
td.appendChild(view);
}
var showPopup = gel("ni.show_attachment_popup").value;
tr.appendChild(td);
table.appendChild(tr);
//If a new attachment is added check if attachments are marked for edge encryption before showing the Download all button
if (!edgeEncryptionEnabledForAttachments && hasAttachments()){
gel("download_all_button").style.display = "inline";
}
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.uploaded', {
sysid: id,
name: fileName,
hoverText: anchor.title,
image: imgSrc,
showRename: allowRename,
showView: showView,
showPopup: showPopup
});
}else{
addAttachmentNameToForm(id, fileName, anchor.title, imgSrc, allowRename, showView, showPopup);
}
if (g_accessibility)
alert(fileName + " " + anchor.title);
}
function refreshLiveFeedAttachments(sys_id, fileName, contentType, iconPath) {
var p = gel('live_feed_message_images');
if (!p)
return;
if (!contentType)
return;
if (contentType.indexOf('image') != 0 || contentType.indexOf('image/tif') == 0)
refreshLiveFeedNonImages(p, sys_id, iconPath, fileName);
else
refreshLiveFeedImages(p, sys_id, fileName);
var container = $('live_feed_image_container');
if (container)
container.show();
}
function refreshLiveFeedNonImages(p, sys_id, iconPath, fileName) {
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = iconPath;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
var span = cel('span');
span.setAttribute('data-id', sys_id);
if ('innerText' in span)
span.innerText = fileName;
else
span.textContet = fileName;
a.appendChild(span);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
function refreshLiveFeedImages(p, sys_id, fileName) {
var imageName = "sys_attachment.do?sys_id=" + sys_id;
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = imageName;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
// this get called after attachments are deleted to update the display
function deletedAttachments(sysIds) {
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.deleted', sysIds);
return;
}
deleteLiveFeedAttachments(sysIds);
var modified = $("attachments_modified");
if (modified)
modified.value = "true";
var header_attachment = $('header_attachment');
gel("deleted_sys_ids").value = ""; // there should be none on the list once we return
var idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var id = idArray[i];
changeCount(attachmentParentSysId, 'decrease');
var e = gel("sys_id_" + id);
var tr = e.parentNode.parentNode;
rel(tr);
e = gel("attachment_" + id);
if (e)
rel(e);
}
var inputs = document.getElementsByTagName("input");
var anAttachment = false;
var i = 0;
while(i < inputs.length && !anAttachment) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
anAttachment = true;
i++;
}
if (!anAttachment) {
var noAttachments = gel("no_attachments");
noAttachments.style.display = "none";
var removeButton = gel("removeButton");
removeButton.disabled = true;
var downloadAllButton = gel("download_all_button");
downloadAllButton.style.display = "none";
gel('delete_button_span').style.display = "none";
hideObject($("header_attachment_list_label"));
if (header_attachment)
header_attachment.style.height = "auto";
var line = $("header_attachment_line");
if (line) {
line.style.visibility = "hidden";
line.style.display = "none";
}
}
gel("please_wait").style.display = "none";
var more_attachments = $('more_attachments');
if (more_attachments && header_attachment)
if( (computeAttachmentWidth() - 20) >= (header_attachment.getWidth() - more_attachments.getWidth()))
more_attachments.style.display = 'block';
else
more_attachments.style.display = 'none';
}
function deleteLiveFeedAttachments(sysIds) {
var p = $('live_feed_message_images');
if (!p)
return;
if (!p.visible())
return;
idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var imgs = p.select("img.live_feed_image_thumbnail");
if (imgs.length < 1)
return;
for (var j=0; j<imgs.length; j++) {
if (imgs[j].getAttribute("data-sys_id") == idArray[i]) {
var elem = imgs[j].up("a.live_feed_attachment_link");
elem.remove();
if (elem.next() && (elem.next().tagName.toLowerCase() == "br"))
elem.next().remove();
}
}
}
if (p.select("img.live_feed_image_thumbnail").length > 0)
return;
var container = $('live_feed_image_container');
if (container)
container.hide();
}
function computeAttachmentWidth() {
var temp = $('header_attachment_list').select('li');
var totalWidth = 0;
for (var i = 0; i < temp.length; i++) {
totalWidth += temp[i].getWidth();
}
return totalWidth;
}
function closeAttachmentWindow() {
GlideModal.prototype.get('attachment').destroy();
}
/**
* Add an input field to the file browser in the dialog.
* This is called when the "Add Another Attachment" button
* is clicked.
* */
function addRowToTable() {
var formRows = $('sys_attachment').select(".attachmentRow");
var input = "<input type='file' title='Attach' " +
"name='attachFile' onchange='checkAndSetAttachButton(); setDeleteButton(this.value);'" +
"size=41 multiple=true />";
var img = "<a href='#' onclick='clearAttachmentField($(this).up().up()); setDeleteButton(this.value);'>" +
"<img src='images/icons/kb_no.gif'/></a>";
var row = "<tr class='attachmentRow'><td> "
+ input + "</td><td align='right'>" + img + "</td></tr>";
formRows.last().insert({ "after" : row });
}
/**
* Download all attachments
*/
function downloadAllAttachments(){
var downloadUrl = window.location.protocol + '//' + window.location.host + '/download_all_attachments.do?sysparm_sys_id=' + attachmentParentSysId;
window.location = downloadUrl;
}
function hasAttachments(){
return document.getElementsByClassName("attachment_sys_id").length > 0;
}</script>
This is what happens when I click on the attach button in the HTML. attachFile is the ID which I am using in my code to run.
<tr class="attachmentRow">
<td id="attachFileCell" colspan="3">
<input name="attachFile" title="" id="attachFile" onchange="checkAndSetAttachButton(); setDeleteButton(this.value); $('attachButton').click();" type="file" size="41" multiple="true" data-original-title="Attach">
<a class="attachfile-delete" style="display: none; cursor: default;" onclick="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);" href="#">
<img src="images/icons/kb_no_disabled.gif">
</a>
<input disabled="" class="attachfile-attach button" id="attachButton" style="display: none;" type="submit" value="Attach">
</td>
</tr>
This is my VBA Code which I used.
Set IE = New SHDocVw.InternetExplorer
IE.Visible = True
IE.Navigate "https://sorry cant share the link as per the company policy"
Do While IE.Busy = True Or IE.READYSTATE <> 4: DoEvents: Loop
Set HTMLDoc = IE.Document
'***************** Save Email
eachitem.SaveAs StrFile, 3
'***************** file link to clipboard
CopyText StrFile
'***************** Attach Email
HTMLDoc.getElementById("header_add_attachment").Click
Application.Wait (Now() + TimeValue("00:00:02"))
'***************** Call external VBS file to handle the pop up then attach
Shell "Explorer.exe " & StrFolderPath & "SNOW.vbs", vbNormalFocus
HTMLDoc.getElementById("attachFile").Click
SendKeys "{Enter}", True
I tried the below method to call the function, but reaching nowhere! Any assistance would be appreciated. I really dont know which function attaches the file to the website and how.
Set HTMLDoc1 = IE.Document.parentWindow
HTMLDoc1.execScript code:="isJEXLExpression(" & StrFile & ")"
HTMLDoc1.execScript code:="checkAndSetAttachButton()"
HTMLDoc1.execScript code:="setDeleteButton(this.value)"
HTMLDoc1.execScript code:="$('attachButton').click()"
HTMLDoc1.execScript code:="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);"
Related
I'm writing a google docs apps script in making a google docs add-on. When the user clicks a button in the sidebar, an apps script function is called named executeSpellChecking. This apps script function makes a remote POST call after getting the document's text.
total time = time that takes from when user clicks the button, until the .withSuccessHandler(, that means until executeSpellChecking returns = 2000 ms
function time = time that takes for the executeSpellChecking call to complete from its start to its end = 1400 ms
t3 = time that takes for the remote POST call to be completed = 800ms
t4 = time that takes for the same remote POST call to complete in a VB.NET app = 200ms
Problems:
Why total time to complete is bigger than total function time by a staggering 600ms, what else happens there? shouldn't they be equal? How can I improve it?
Why t3 is bigger than t4 ? Shouldn't they be equal? Is there something wrong with POST requests when happening from .gs? How can I improve it ?
the code is (sidebar.html):
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
//var t1 = new Date().getTime();
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
//var t2 = new Date().getTime();
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//alert("total time to complete:" + (t2-t1) + "###" + go_TextAndTranslation.time);
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
and the called function code is (spellcheck.gs):
function executeSpellChecking(origin, dest, savePrefs) {
//var t1 = new Date().getTime();
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
//var t11 = new Date().getTime();
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
//var t22 = new Date().getTime();
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
//var t2 = new Date().getTime();
console.timeEnd("function time")
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}
Thank you in advance for any help.
EDIT: I updated the code to use console.time according to the suggestion, the results are:
total time: 2048.001953125 ms
Jun 21, 2021, 3:01:40 PM Debug POST time: 809ms
Jun 21, 2021, 3:01:41 PM Debug function time: 1408ms
So the problem is not how time is measured. function time is 1400ms, while the time it takes to return is 2000ms, a difference of 600ms and the POST time is a staggering 800ms, instead of 200ms it takes in VB.net to make the exact same POST call.
Use console.time() and console.timeEnd():
https://developers.google.com/apps-script/reference/base/console
I modified the code for you. console.timeEnd() outputs the time duration in the console automatically, so I removed the alert for you that showed the time difference.
You might want the strings that I used as the parameter as some sort of constant variable, so there are no magic strings used twice. I hope this is of use to you.
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
function executeSpellChecking(origin, dest, savePrefs) {
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
console.timeEnd("function time");
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}
I've created a script to create a new array called spots, here is the script:
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
alert(textArray);
} else {
alert("No Swatches Selected.");
}
}
This script alerts the following:
var spots = new Array(
"Yellow 012 C",
"Bright Red C",
);
How do I now alert the contents of that array i.e. Yellow 012 C, Bright Red C
I have tried using:
alert(spots);
But I get the error undefined maybe because the array is created on the fly and its not placed in the script?
UPDATE:
As per the comments, I have edited the script adding:
var spots = [];
spots.push(color.spot)
alert(spots);
I now get the following error: undefined is not an object
Here's the full script
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
var spots = [];
spots.push(color.spot)
alert(spots);
} else {
alert("No Swatches Selected.");
}
}
Try
function main() {
//var doc = app.activeDocument;
var selectedSwatches
= [{"color":{"spot":{"color":"#ff0000","name":"red"},"typename":"SpotColor"}}
,{"color":{"spot":{"color":"#000000","name":"black"},"typename":"SpotColor"}}];
// = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
var spots = [];
if (selectedSwatches.length > 0) {
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
spots.push(color.spot.name);
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
alert(spots.toString());
} else {
alert("No Swatches Selected.");
}
}
<button onclick="main()">Main</>
Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* 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
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.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 = true;
// 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.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
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;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.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;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
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 = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
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);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
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();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// 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(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.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);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.
I'm integrating a widget into my page (Houzz). It works, but only if I remove all xlinks in my SVGs. If there are any xlinks, I get the error:
TypeError: elem.className.split is not a function
The SVG is:
<svg version="1.1" id="Layer_4_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="1309.016px" height="634.008px" viewBox="0 0 1309.016 634.008" enable-background="new 0 0 1309.016 634.008"
xml:space="preserve" class="js-animate" style="max-width: 100%;">
<a xlink:type="simple" xlink:href="/meet-the-team"></a>
</svg>
The script is:
(function(d,s,id){if(!d.getElementById(id)){var js=d.createElement(s);js.id=id;js.async=true;js.src="//platform.houzz.com/js/widgets.js?"+(new Date().getTime());var ss=d.getElementsByTagName('script')[0];ss.parentNode.insertBefore(js,ss);}})(document,"script","houzzwidget-js");
I've created a fiddle, but that's displaying different behaviour - I have to remove the width / height from the svg to make the widget work:
https://jsfiddle.net/v0fkr8jx/
My test page:
http://uprightconstruction.co.uk/index2
Here's the Houzz script being referenced. The error is around line 16 going by Firebug:
window.hzmr = window.hzmr || []; window.hzmr.push("widgets:2406");
(function() {
function createIFrame(width, height) {
var iframeElem = document.createElement('iframe');
iframeElem.setAttribute("scrolling","no");
iframeElem.allowTransparency = true;
iframeElem.border = 0;
iframeElem.frameBorder = 0;
iframeElem.style.border = 'none';
iframeElem.width = width;
iframeElem.height = height;
return iframeElem;
}
function containsClassName(elem, className) {
var classNames = elem.className.split(' ');
for(var i=0; i<classNames.length; i++) {
if(className == classNames[i]) {
return true;
}
}
return false;
}
function cleanLocale(locale) {
var knownLocales = {"en-us":true,"en-gb":true,"en-au":true,"de-de":true,"fr-fr":true,"ru-ru":true,"ja-jp":true,"it-it":true,"es-es":true,"da-dk":true,"nb-no":true,"fi-fi":true,"sv-se":true,"en-ie":true,"en-nz":true,"en-sg":true,"en-in":true};
if(locale && locale.toLowerCase() in knownLocales) {
return locale.toLowerCase();
}
return 'en-us';
}
function processWidgets(domId) {
var links = [];
if(typeof domId == 'string') {
if(domId.charAt(0) == '#') {
domId = domId.substr(1);
}
var elem = document.getElementById(domId);
if(elem) {
links.push(elem);
}
} else if(typeof domId != 'undefined' && ('nodeName' in domId)) {
links.push(domId);
} else {
links = document.getElementsByTagName('a');
}
var pid = new Date().getTime() + '' + Math.floor(Math.random()*1000000);
var houzzLinks = [];
var houzzReviews = [];
for (var i=0; i < links.length; i++) {
if(containsClassName(links[i],'houzz-share-button')) {
houzzLinks.push(links[i]);
} else if(containsClassName(links[i], 'houzz-review-widget')) {
houzzReviews.push(links[i]);
}
}
for (var i=0; i < houzzReviews.length; i++) {
var review = houzzReviews[i];
var pro = review.getAttribute('data-pro');
var mini = review.getAttribute('data-size');
mini = (mini == 'mini');
var locale = cleanLocale(review.getAttribute('data-locale'));
var iframeWidth = mini?225:300;
var iframeHeight = mini?130:435;
if(pro) {
var reviewUrls = {"en-us":"http:\/\/www.houzz.com\/reviewWidget","en-gb":"http:\/\/www.houzz.co.uk\/reviewWidget","en-au":"http:\/\/www.houzz.com.au\/reviewWidget","de-de":"http:\/\/www.houzz.de\/reviewWidget","fr-fr":"http:\/\/www.houzz.fr\/reviewWidget","ru-ru":"http:\/\/www.houzz.ru\/reviewWidget","ja-jp":"http:\/\/www.houzz.jp\/reviewWidget","it-it":"http:\/\/www.houzz.it\/reviewWidget","es-es":"http:\/\/www.houzz.es\/reviewWidget","da-dk":"http:\/\/www.houzz.dk\/reviewWidget","nb-no":"http:\/\/www.houzz.no\/reviewWidget","fi-fi":"http:\/\/www.houzz.fi\/reviewWidget","sv-se":"http:\/\/www.houzz.se\/reviewWidget","en-ie":"http:\/\/www.houzz.ie\/reviewWidget","en-nz":"http:\/\/www.houzz.co.nz\/reviewWidget","en-sg":"http:\/\/www.houzz.com.sg\/reviewWidget","en-in":"http:\/\/www.houzz.in\/reviewWidget"};
var iframeSrc = reviewUrls[locale] + '/' + encodeURIComponent(pro) + '/' + (mini?'mini':'');
var iframeElem = createIFrame(iframeWidth, iframeHeight);
review.parentNode.replaceChild(iframeElem, review);
iframeElem.src = iframeSrc;
}
}
for (var i=0; i < houzzLinks.length; i++) {
var link = houzzLinks[i];
var imageURL = link.getAttribute('data-img');
var linkURL = link.getAttribute('data-url');
var title = link.getAttribute('data-title');
var showCount = link.getAttribute('data-showcount') == '1';
var hzID = link.getAttribute('data-hzid');
var whiteBg = link.getAttribute('data-whitebg');
var format = link.getAttribute('data-format');
var locale = cleanLocale(link.getAttribute('data-locale'));
var identifier = i + '' + Math.floor(Math.random()*1000000);
link.id = 'hzbtn' + identifier;
var referer = document.location.href;
var buttonWidths = {"en-us":52,"en-gb":52,"en-au":52,"de-de":75,"fr-fr":88,"ru-ru":52,"ja-jp":52,"it-it":52,"es-es":52,"da-dk":52,"nb-no":52,"fi-fi":52,"sv-se":52,"en-ie":52,"en-nz":52,"en-sg":52,"en-in":52};
var buttonWidth = buttonWidths[locale];
var buttonUrls = {"en-us":"http:\/\/www.houzz.com\/buttonWidget","en-gb":"http:\/\/www.houzz.co.uk\/buttonWidget","en-au":"http:\/\/www.houzz.com.au\/buttonWidget","de-de":"http:\/\/www.houzz.de\/buttonWidget","fr-fr":"http:\/\/www.houzz.fr\/buttonWidget","ru-ru":"http:\/\/www.houzz.ru\/buttonWidget","ja-jp":"http:\/\/www.houzz.jp\/buttonWidget","it-it":"http:\/\/www.houzz.it\/buttonWidget","es-es":"http:\/\/www.houzz.es\/buttonWidget","da-dk":"http:\/\/www.houzz.dk\/buttonWidget","nb-no":"http:\/\/www.houzz.no\/buttonWidget","fi-fi":"http:\/\/www.houzz.fi\/buttonWidget","sv-se":"http:\/\/www.houzz.se\/buttonWidget","en-ie":"http:\/\/www.houzz.ie\/buttonWidget","en-nz":"http:\/\/www.houzz.co.nz\/buttonWidget","en-sg":"http:\/\/www.houzz.com.sg\/buttonWidget","en-in":"http:\/\/www.houzz.in\/buttonWidget"};
var iframeSrc = buttonUrls[locale] + '?url='
+ encodeURIComponent(linkURL);
if(imageURL) {
iframeSrc += '&img=' + encodeURIComponent(imageURL);
}
if(title) {
iframeSrc += '&title=' + encodeURIComponent(title);
}
if(showCount) {
iframeSrc += '&count=1';
}
if(whiteBg) {
var whiteBgValue = 0;
if(String(whiteBg) == '1' || whiteBg.toLowerCase() == 'true') {
whiteBgValue = 2;
} else if(String(whiteBg) == '0' || whiteBg.toLowerCase() == 'false') {
whiteBgValue = 1;
}
iframeSrc += '&whiteBg=' + encodeURIComponent(whiteBgValue);
}
if(hzID) {
iframeSrc += '&hzid=' + encodeURIComponent(hzID);
}
iframeSrc += '&locale=' + encodeURIComponent(locale);
iframeSrc += '&ref=' + encodeURIComponent(referer);
iframeSrc += '&pid=' + encodeURIComponent(pid);
if(format == 'custom') {
if(link.getAttribute('data-loaded') == '1') { continue; }
iframeSrc += '&fmt=' + encodeURIComponent(format);
iframeSrc += '&domid=' + encodeURIComponent(identifier);
var extElem = document.createElement('script');
extElem.setAttribute('type','text/javascript');
extElem.id = 'hzjs' + encodeURIComponent(identifier);
extElem.src = iframeSrc;
link.parentNode.appendChild(extElem);
} else {
var iframeElem = createIFrame(buttonWidth + (showCount?57:0), 20);
link.parentNode.replaceChild(iframeElem, link);
iframeElem.src = iframeSrc;
}
}
}
window.houzz = window.houzz || {};
window.houzz.processWidgets = processWidgets;
processWidgets();
})();
Any ideas about what's causing this?
This is because the script you are loading is getting all elements named a.
This will take HTML and SVG <a> elements without distinction.
The problem is that for SVG elements, the class attribute or className property is animatable. Which means that when you call a.className, you'll get an SVGAnimatedString Object, composed of two strings in two keys : baseVal and animVal.
Each of these keys has a split method, but not the SVGAnimatedString itself.
So the code should be modified to either find out if this is an HTML <a> (by checking its namespaceURI property), or to check if the split method is available before calling it, or by calling elem.getAttribute('class') instead of elem.className.
Hello Auto completion is not working well in my application.When we type a name it displays only a blank list[ Screenshots attached ].
Controller Code
public function list_UserByName($letters)
{
if(strpos($letters, ","))
{
$letters1 = explode(",",$letters);
$lecount = count($letters1);
$letters = $letters1[$lecount-1];
}
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
$response=$this->user_model->getAutoUserList($letters);
}
Model Code
public function getAutoUserList($letters)
{
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//AND user_type='C' AND user_status='A'
$query="select * from gm_users where uname Like '%$letters%'";
$result_query =$this->db->query($query);
foreach($result_query->result() as $result)
{
//echo "###".$result."|";
//$pinlevel =$this->functions->get_pinlevel($result->pinLevel);
//echo $result->userId."###".$result->uname." [ ".$pinlevel." ] "."|";
echo $result->userId."###".$result->uname."".$result->address." ".$result->city."|";
}
}
billing.php
<input type="text" autocomplete="off" size="20" name="txtname" id="txtname" onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);" value=""/>
ajax-dynamic-list.js
/************************************************************************************************************
(C) www.dhtmlgoodies.com, April 2006
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var ajaxBox_offsetX = 25;
var ajaxBox_offsetY = 5;
var ajax_list_externalFile = site_url+'/catalog/list_UserByName'; // Path to external file
var minimumLettersBeforeLookup = 1; // Number of letters entered before a lookup is performed.
var ajax_list_objects = new Array();
var ajax_list_cachedLists = new Array();
var ajax_list_activeInput = false;
var ajax_list_activeItem;
var ajax_list_optionDivFirstItem = false;
var ajax_list_currentLetters = new Array();
var ajax_optionDiv = false;
var ajax_optionDiv_iframe = false;
var ajax_list_MSIE = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
var currentListIndex = 0;
function ajax_getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null){
returnValue += inputObj.offsetTop;
}
return returnValue;
}
function ajax_list_cancelEvent()
{
return false;
}
function ajax_getLeftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
// Edited
function ajax_option_setValue_bkp(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
val = ajax_list_activeInput.value.split(',');
vals = '';
count = val.length - 1;
for(i=0;i<count;i++)
{
vals = vals + val[i] + ',';
}
ajax_list_activeInput.value = vals + tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_option_setValue(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
ajax_list_activeInput.value = tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_options_hide()
{
if(ajax_optionDiv)ajax_optionDiv.style.display='none';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='none';
}
function ajax_options_rollOverActiveItem(item,fromKeyBoard)
{
if(ajax_list_activeItem)ajax_list_activeItem.className='optionDiv';
item.className='optionDivSelected';
ajax_list_activeItem = item;
if(fromKeyBoard){
if(ajax_list_activeItem.offsetTop>ajax_optionDiv.offsetHeight){
ajax_optionDiv.scrollTop = ajax_list_activeItem.offsetTop - ajax_optionDiv.offsetHeight + ajax_list_activeItem.offsetHeight + 2 ;
}
if(ajax_list_activeItem.offsetTop<ajax_optionDiv.scrollTop)
{
ajax_optionDiv.scrollTop = 0;
}
}
}
function ajax_option_list_buildList(letters,paramToExternalFile)
{
ajax_optionDiv.innerHTML = '';
ajax_list_activeItem = false;
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length<=1){
ajax_options_hide();
return;
}
ajax_list_optionDivFirstItem = false;
var optionsAdded = false;
for(var no=0;no<ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length;no++){
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].length==0)continue;
optionsAdded = true;
var div = document.createElement('DIV');
var items = ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].split(/###/gi);
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length==1 && ajax_list_activeInput.value == items[0]){
ajax_options_hide();
return;
}
div.innerHTML = items[items.length-1];
div.id = items[0];
div.className='optionDiv';
div.onmouseover = function(){ ajax_options_rollOverActiveItem(this,false) }
div.onclick = ajax_option_setValue;
if(!ajax_list_optionDivFirstItem)ajax_list_optionDivFirstItem = div;
ajax_optionDiv.appendChild(div);
}
if(optionsAdded){
ajax_optionDiv.style.display='block';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='';
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}
}
function ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,whichIndex)
{
if(whichIndex!=currentListIndex)return;
var letters = inputObj.value;
var content = ajax_list_objects[ajaxIndex].response;
var elements = content.split('|');
//alert(content);
ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()] = elements;
ajax_option_list_buildList(letters,paramToExternalFile);
}
function ajax_option_resize(inputObj)
{
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
}
function ajax_showOptions(inputObj,paramToExternalFile,e)
{
document.getElementById('saleUserId').value='';
if(e.keyCode==13 || e.keyCode==9)return;
if(ajax_list_currentLetters[inputObj.name]==inputObj.value)return;
if(!ajax_list_cachedLists[paramToExternalFile])ajax_list_cachedLists[paramToExternalFile] = new Array();
ajax_list_currentLetters[inputObj.name] = inputObj.value;
if(!ajax_optionDiv){
ajax_optionDiv = document.createElement('DIV');
ajax_optionDiv.id = 'ajax_listOfOptions';
document.body.appendChild(ajax_optionDiv);
if(ajax_list_MSIE){
ajax_optionDiv_iframe = document.createElement('IFRAME');
ajax_optionDiv_iframe.border='0';
ajax_optionDiv_iframe.style.width = ajax_optionDiv.clientWidth + 'px';
ajax_optionDiv_iframe.style.height = ajax_optionDiv.clientHeight + 'px';
ajax_optionDiv_iframe.id = 'ajax_listOfOptions_iframe';
document.body.appendChild(ajax_optionDiv_iframe);
}
var allInputs = document.getElementsByTagName('INPUT');
for(var no=0;no<allInputs.length;no++){
if(!allInputs[no].onkeyup)allInputs[no].onfocus = ajax_options_hide;
}
var allSelects = document.getElementsByTagName('SELECT');
for(var no=0;no<allSelects.length;no++){
allSelects[no].onfocus = ajax_options_hide;
}
var oldonkeydown=document.body.onkeydown;
if(typeof oldonkeydown!='function'){
document.body.onkeydown=ajax_option_keyNavigation;
}else{
document.body.onkeydown=function(){
oldonkeydown();
ajax_option_keyNavigation() ;}
}
var oldonresize=document.body.onresize;
if(typeof oldonresize!='function'){
document.body.onresize=function() {ajax_option_resize(inputObj); };
}else{
document.body.onresize=function(){oldonresize();
ajax_option_resize(inputObj) ;}
}
}
if(inputObj.value.length<minimumLettersBeforeLookup){
ajax_options_hide();
return;
}
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
ajax_list_activeInput = inputObj;
ajax_optionDiv.onselectstart = ajax_list_cancelEvent;
currentListIndex++;
if(ajax_list_cachedLists[paramToExternalFile][inputObj.value.toLowerCase()]){
ajax_option_list_buildList(inputObj.value,paramToExternalFile,currentListIndex);
}else{
var tmpIndex=currentListIndex/1;
ajax_optionDiv.innerHTML = '';
var ajaxIndex = ajax_list_objects.length;
ajax_list_objects[ajaxIndex] = new sack();
var search_key = inputObj.value.replace(" ","+");
//search_key1 = search_key.replace(",",",");
var url = ajax_list_externalFile + '/' +search_key;
ajax_list_objects[ajaxIndex].requestFile = url; // Specifying which file to get
ajax_list_objects[ajaxIndex].onCompletion = function(){ ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,tmpIndex); }; // Specify function that will be executed after file has been found
ajax_list_objects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words
return a.length;
}
function ajax_option_keyNavigation(e)
{
if(document.all)e = event;
if(!ajax_optionDiv)return;
if(ajax_optionDiv.style.display=='none')return;
if(e.keyCode==38){ // Up arrow
if(!ajax_list_activeItem)return;
if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
}
if(e.keyCode==40){ // Down arrow
if(!ajax_list_activeItem){
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}else{
if(!ajax_list_activeItem.nextSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
}
}
/*if(e.keyCode==13 || e.keyCode==9){ // Enter key or tab key
if(ajax_list_activeItem && ajax_list_activeItem.className=='optionDivSelected')ajax_option_setValue(false,ajax_list_activeItem);
if(e.keyCode==13)return false; else return true;
}
if(e.keyCode==27){ // Escape key
ajax_options_hide();
}*/
}
//document.documentElement.onclick = autoHideList;
function autoHideList(e)
{
if(document.all)e = event;
if (e.target) source = e.target;
else if (e.srcElement) source = e.srcElement;
if (source.nodeType == 3) // defeat Safari bug
source = source.parentNode;
if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea')ajax_options_hide();
}
Am a beginner in php as well as Codeigniter
Just echo your data in your controller
change
$response=$this->user_model->getAutoUserList($letters);
To
echo $this->user_model->getAutoUserList($letters);
change
onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);
to
onkeyup="ajax_showOptions(this,'list_UserByName',event);
there is a question on this topic on stackoverflow, but an entire different process.
My Codeigniter autocomplete with ajax