Changing DOM properties inside AJAX call not working - javascript

I have a function which makes an AJAX call and depending on the answer, sets the colour of an input. The function core itself works fine. However, when it comes to changing the colour of the input, it is not working.
function Nueva_Red() {
var e1 = document.getElementById("rrss_tipo");
var e2 = document.getElementById("rrss_usuario");
var e3 = document.getElementById("redes");
var e4 = document.getElementById("alta_nueva_red");
var id_red = e1.options[e1.selectedIndex].value;
var red = e1.options[e1.selectedIndex].text;
var usuario = e2.value;
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
if ((id_red > 0) && (usuario != "")) {
var datastr = 'seccion=rrss_check&dato=' + id_red + "|" + usuario;
$.ajax({
type: 'GET',
url: 'validacion.php',
data: datastr,
success: function(html) {
if (html == 1) {
document.getElementById("nuevas_rrss").style.visibility = "visible";
document.getElementById("nuevas_rrss").style.display = "inline-block";
var opcion = document.createElement("option");
opcion.value = id_red + "-" + usuario;
opcion.innerHTML = red + " -> " + usuario;
e3.appendChild(opcion);
e1.value = 0;
e2.value = "";
e2.title = "";
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
} else {
e2.title = html;
e2.style.backgroundColor = error_error;
e2.style.borderColor = error_error;
}
},
error: function(html) {
e2.style.borderColor = error_app;
e2.style.backgroundColor = error_app;
}
});
}
}
Thank you!

Related

Upload a file to a web page as an attachment using VBA

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);"

CSS to style javascript dynamically created table

I'm needing to style a table that's dynamically created by javascript. I know how to style it if it were just a static HTML table but this is different and I'm not too familiar with javascript. Here is the javascript code:
[var aryPortalList = \[\];
function getPortalList() {
var wP = window.location.protocol;
var wH = window.location.host;
var wPath = "ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get";
//http://webfocusclidev:8080/ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get;
var webfocusAPI = wP + "//" + wH + "/" + wPath;
$.ajax({
type: "GET",
async: false,
url: webfocusAPI,
dataType: 'xml',
success: function(xml) {
$(xml).find('children').children().each(function() {
var portal = { Name: $(this).attr('bipName'),
Link: "/ibi_apps/bip/portal" + $(this).attr('bipPath'),
IconLink: "/ibi_apps/WFServlet.ibfs?IBFS1_action=RUNFEX&IBFS_path=" + $(this).attr('bipIconPath')
}; //var portal
console.log("portal.name=" + portal.Name);
if (portal.Name != "GlobalBI") aryPortalList.push(portal);
}); //each
console.log("Portals in List = " + aryPortalList.length);
} //success function
}); //ajax
}
function displayPortalList_Icon() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
var img = $("<img>").attr("src", aryPortalList\[j\].IconLink);
img.width("100px");
img.height("100px");
console.log("hTxt=" + hTxt);
hLink.append(img);
cell.append(hTxt);
cell.append(hLink);
row.append(cell);
bRowAdded = false;
if ((j+1) % 4 == 0) {
hTbl.append(row);
bRowAdded = true;
var row = $('<tr></tr>').addClass('ingrPL_row');
}
}
if (!bRowAdded) {
hTbl.append(row);
}
$("#portallist").html(hTbl);
}
}
function displayPortalList_List() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var row = $('<tr></tr>').addClass('ingrPL_row');
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
console.log("hTxt=" + hTxt);
hLink.append(hTxt);
cell.append(hLink);
row.append(cell);
hTbl.append(row);
}
$("#portallist").html(hTbl);
console.log("portal.name=" + portal.Name);
}
}][1]
And I've attached a photo of how the 'portal' looks.
What I need to do is space out the icons more and have the title's on the bottom of the icons, to look more like an 'iphone app'
Any help is greatly appreciated.
you can style it in the same way you style static elements
looking at your code I can see the table have an ID and the rows have classes
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
so you can select those in your CSS file
CSS
#tbl_portallist {
/*table style here */
}
#tbl_portallist th {
/*table head style here*/
}
#tbl_portallist tr {
/*table row style here*/
}
#tbl_portallist td {
/*table data (cell) style here*/
}

Creating div and adding a background image to it

I've managed to make a div in the place where I wanted it to be, but when it comes to adding a background image, I just can't do it.
I'm creating divs with the loop and then I'm trying to add a background image to it in the same loop. I don't know if that's the problem or something else, if that's the case, please help me make another.
I tried doing something like itemContainer[i] but I can't get that to work either.
Update: the reason is that my array is empty, don't really know what I'm doing wrong though.
var cicon = [];
$.ajax({
url: '/json/test.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.test).each(function(index, value) {
cicon.push(value.Icon);
/*console.log(value.Icon) works here,
so there's something wrong when I'm adding it to the array.*/
});
}
});
for (var i = 0, n = 10; i < n; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
If anyone is wondering, the array contains urls that look like this: https://steamcdn-a.akamaihd.net/apps/440/icons/earbuds.f6dc85683202f2530ae8728880f4a47d4b013ea8.png
If you re-declare:
var cicon = [];
you are simply emptying the array variable. (how do i empty an array in javascript)
Example:
var cicon = [];
function doWork() {
for (var i = 0; i < cicon.length; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
}
$(function () {
$.ajax({
url: '/json/BotCopper.json',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
$(data.BotCopper).each(function (index, value) {
cicon.push(value.Icon);
doWork();
});
},
error: function (jqXHR, textStatus, errorThrown) {
// this is only for test
cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];
doWork();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page"></div>
Instead, removing the line:
var cicon = [];
the result is:
window.onload = function() {
var cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];
for (var i = 0, n = 10; i < n; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
}
<div id="page"></div>
There is nothing wrong with your script but you need elements in cicon. e.g
var cicon = ["url1","url2",...];
Check here for a working example: Div Background image

Codeigniter Auto completion is not working

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

Creating JSON request data with javascript

I need to create data for a JSON request with the inputs taken from an html form. The data format that I want to generate is like below.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{
"inputParams":[
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
},
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
}
],
"outputParams":[
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
},
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
}
]
}
}
My code looks like below;
var jasonRequest = {};
jasonRequest["applicationName"] = appName;
jasonRequest["cpuCount"] = cpuCount;
jasonRequest["hostdescName"] = hostName;
jasonRequest["maxMemory"] = maxMemory;
jasonRequest["maxWallTime"] = ""; //TODO
jasonRequest["minMemory"] = ""; //TODO
jasonRequest["nodeCount"] = nodeCount;
jasonRequest["processorsPerNode"] = ""; //TODO
var inArray = new Array();
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jasonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jasonRequest));
The data created by this code is like below. I could use strings and create the message by concatenating it but I don't think that is a nice way of doing this. As you can see the inputParams and outputParams are not properly populated. Can you suggest how can I properly generate this message.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{"inputParams":"","outputParams":[]}}
[EDIT]
My code looks like below.
$(document).ready(function(){
var inputCount = 0;
var outputCount = 0;
$("p1").live("click", function(){
inputCount++;
$(this).after("<br/>");
$(this).after("Input Name *:" +
"<input type="text" id="inputName" + inputCount + "" name="inputName" + inputCount + "" value="echo_input" size="50"><br/>");
$(this).after("Input Type *:" +
"<input type="text" id="inputType" + inputCount + "" name="inputType" + inputCount + "" value="String" size="50"><br/>");
});
$("p2").live("click", function(){
$(this).after("Output Name *:" +
"<input type="text" id="outputName" + outputCount + "" name="outputName" + outputCount + "" value="echo_output" size="50"><br/>");
$(this).after();
$(this).after("Output Type *:" +
"<input type="text" id="outputType" + outputCount + "" name="outputType" + outputCount + "" value="String" size="50"><br/>");
});
$('[name="btn2"]').click(function(){
var appName = $("#appName1").val();
var exeuctableLocation = $("#exeuctableLocation1").val();
var scratchWorkingDirectory = $("#scratchWorkingDirectory1").val();
var hostName = $("#hostName1").val();
var projAccNumber = $("#projAccNumber1").val();
var queueName = $("#queueName1").val();
var cpuCount = $("#cpuCount1").val();
var nodeCount = $("#nodeCount1").val();
var maxMemory = $("#maxMemory1").val();
var serviceName = $("#serviceName1").val();
var inputName1 = $("#inputName1").val();
var inputType1 = $("#inputType1").val();
var outputName = $("#outputName1").val();
var outputType = $("#outputType1").val();
var jsonRequest = {};
jsonRequest["applicationName"] = appName;
jsonRequest["cpuCount"] = cpuCount;
jsonRequest["hostdescName"] = hostName;
jsonRequest["maxMemory"] = maxMemory;
jsonRequest["maxWallTime"] = ""; //TODO
jsonRequest["minMemory"] = ""; //TODO
jsonRequest["nodeCount"] = nodeCount;
jsonRequest["processorsPerNode"] = ""; //TODO
var inArray = [];
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jsonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jsonRequest));
$.ajax({
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://localhost:7080/airavata-registry-rest-services/registry/api/applicationdescriptor/build/save/test",
data: jasonRequest
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
What's inputCount and outputCount? Seems like they are zero or NaN or something, so you get empty arrays. Yet, your code will still print "inputParams":[] instead of "inputParams":"".
To get a nice output (not that it would be needed for your app, only for debugging), you can use the third parameter of JSON.stringify.

Categories