Creating JSON request data with javascript - 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.

Related

How to trigger default rendering in Sharepoint 2013 List View via JS Link

I'm building a custom layout for a SharePoint list via JS Link...
At the moment I'm rendering all by myself, but for some more complex items (Taxonomy, URLs, etc.) it would be great to be able to trigger the custom rendering of SharePoint.
Is this possible somehow for single field types?
var csListView = csListView || {};
csListView.ListBody = '<div class="datagrid"><table><thead>{LIST_HEADER}</thead>{LIST_BODY}<tfoot><tr><td colspan="{FIELD_COUNT}"><div class="paging">{PAGINATION}</div></td></tr></tfoot></table></div>';
csListView.HeaderRow = '<tr>{HEADER_ITEMS}</tr>';
csListView.HeaderItem = '<th>{HEADER_ITEM}</th>';
csListView.BodyRow = '<tr class="{ALT_CLASS}">{LIST_ITEMS}</tr>';
csListView.BodyItem = '<td>{LIST_ITEM}</td>';
csListView.CustomizeFieldRendering = function ()
{
var fieldJsLinkOverride = {};
fieldJsLinkOverride.Templates = {};
fieldJsLinkOverride.Templates.Body = csListView.RenderBody;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldJsLinkOverride);
};
csListView.RenderBody = function (ctx) {
var colspan = ctx.ListSchema.Field.length;
var html = '';
var itemHtml = '';
var itemsHtml = '';
var rowHtml = '';
var bodyHtml = '';
var paginationHtml = '';
var headerItemsHtml = '';
var headerHtml = '';
//Render Header fields
for (var i = 0; i < ctx.ListSchema.Field.length; i++) {
var sortUrl = location.search + '?SortField=' + ctx.ListSchema.Field[i].RealFieldName + '&SortDir=Desc';//ctx.HttpRoot + ctx.listUrlDir + '/&' + ctx.ListSchema.FieldSortParam
var item = '' + ctx.ListSchema.Field[i].DisplayName + '';
headerItemsHtml += csListView.HeaderItem.replace('{HEADER_ITEM}', ctx.ListSchema.Field[i].DisplayName);
}
headerHtml = csListView.HeaderRow.replace('{HEADER_ITEMS}', headerItemsHtml);
//Go through all rows
for (var i = 0; i < ctx.ListData.Row.length; i++) {
var cssClass = (i % 2 == 0) ? 'alt' : '';
//Go through all fields
itemsHtml = '';
for (var j = 0; j < ctx.ListSchema.Field.length; j++) {
var item = csListView.renderField(ctx, ctx.ListSchema.Field[j], ctx.ListData.Row[i]);
itemHtml = csListView.BodyItem.replace('{LIST_ITEM}',item);
itemsHtml += itemHtml;
}
rowHtml = csListView.BodyRow.replace('{LIST_ITEMS}',itemsHtml);
rowHtml = rowHtml.replace('{ALT_CLASS}', cssClass);
bodyHtml += rowHtml;
}
html = csListView.ListBody.replace('{LIST_BODY}', bodyHtml);
html = html.replace('{PAGINATION}', renderPaging(ctx));
html = html.replace('{FIELD_COUNT}', colspan);
html = html.replace('{LIST_HEADER}', headerHtml);
return html;
};
csListView.renderField = function (ctx, fieldData, rowData) {
return rowData[fieldData.RealFieldName];
}
To change a the view of a field you could use this
var ctx = {};
ctx.Templates = {};
ctx.Templates.Fields = {'ColumnName': { 'View' : '<b><#=ctx.CurrentItem.ColumnName#></b>' }};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
Does that answer your question?

Run jQuery code after AJAX jQuery load()

How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?
function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.
Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});

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

Javascript XML same element name

I have an XML file containing the same element name more than once, like below. I can only retrieve the first one. Would like to know how to retrieve all 4 "comments" using JavaScript. Thanks!
<FRIENDSSTATUS>
<STATUSFRIENDS id="2">
<STATUS>Life begins at the end of your comfort zone</STATUS>
<DATETIME>2012-10-30 10:32:28</DATETIME>
<FIRSTNAME>Malcolm</FIRSTNAME>
<LASTNAME>Landgraab</LASTNAME>
<COMMENTS datetime="2012-11-18 22:13:28" firstname="Ian" lastname="Tellerman">rr</COMMENTS>
<COMMENTS datetime="2012-11-18 22:13:39" firstname="Ian" lastname="Tellerman">hello</COMMENTS>
<COMMENTS datetime="2012-11-19 14:36:24" firstname="Ian" lastname="Tellerman">test</COMMENTS>
<COMMENTS datetime="2012-11-19 14:45:52" firstname="Ian" lastname="Tellerman">test4</COMMENTS>
</STATUSFRIENDS>
<STATUSFRIENDS id="3">
<STATUS>Prometheus. Fantastic film!!!!</STATUS>
<DATETIME>2012-10-30 10:32:28</DATETIME>
<FIRSTNAME>Mansa</FIRSTNAME>
<LASTNAME>Bendett</LASTNAME>
<COMMENTS datetime="2012-11-18 22:14:46" firstname="Ian" lastname="Tellerman">wrong</COMMENTS>
</STATUSFRIENDS>
</FRIENDSSTATUS>
The javascript codes:
xmlDoc = xmlhttp.responseXML;
$table = "<table border='1'>";
var element = xmlDoc.getElementsByTagName("FRIENDSSTATUS");
var elements = xmlDoc.getElementsByTagName("STATUSFRIENDS");
var comments = xmlDoc.getElementsByTagName("COMMENTS");
if(xmlDoc.documentElement !== null)
{
var root;
if (navigator.userAgent.indexOf("Firefox") > 0 )
var root = element[0].childElementCount;
if (navigator.userAgent.indexOf("MSIE") > 0 )
var root = xmlDoc.documentElement.childNodes.length;
for(i=0; i<root; i++){
$strStats = "";
$strComments = "";
$strDateTime = "";
$strFirstname = "";
$strLastname = "";
$strCommentDateTime = "";
$strCommentFirstName = "";
$strCommentLastName = "";
$strStatusID = "";
if(navigator.userAgent.indexOf("Firefox") > 0 ){
for(y=0;y < elements[i].childElementCount;y++)
{
$strStatusID = elements[i].getAttribute("id");
if(strStatus = elements[i].getElementsByTagName("STATUS"))
{
$strStats = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("DATETIME"))
{
$strDateTime = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("FIRSTNAME"))
{
$strFirstname = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("LASTNAME"))
{
$strLastname = strStatus[0].firstChild.nodeValue;
}
if(strComm = elements[i].getElementsByTagName("COMMENTS"))
{
$strComments = strComm[0].firstChild.nodeValue;
$strCommentDateTime = comments[i].getAttribute("datetime");
$strCommentFirstName = comments[i].getAttribute("firstname");
$strCommentLastName = comments[i].getAttribute("lastname");
$strComments += "<br>" + $strCommentFirstName + " " + $strCommentLastName + " " + $strCommentDateTime + "</br></br>";
}
$strStats = $strStats + " " + $strLastname + " " + $strFirstname + " " + $strDateTime;
$strFullName = $strFirstname + " " + $strLastname;
$strDateTime = "";
$strFirstname = "";
$strLastname = "";
}
}
Assign your XML to a variable, (myXmlString in this example), and read it as follows:
var parser=new DOMParser();
doc=parser.parseFromString(myXmlString,'text/xml');
var comments = doc.getElementsByTagName("COMMENTS") // Returns a array of those "comments".
An example of how to access the comments of the first STATUSFRIENDS. jsFiddle demo here.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml(xmlStr); // assuming xmlStr contains your XML
var commentsList = xml.documentElement.childNodes[0].getElementsByTagName("COMMENTS");
var output = "";
for(var i=0; i<commentsList.length; i++)
{
output += commentsList[i].firstChild.nodeValue + "<br />";
}
document.getElementById("comments").innerHTML = output;
Something like this:
var str = 'your XML as a string',
parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
}
var nodes = xml.childNodes[0].getElementsByTagName('COMMENTS');
var i, l = nodes.length, comments = [];
for (i = 0; i < l; i++) {
comments.push({
firstname: nodes[i].getAttribute('firstname'),
lastname: nodes[i].getAttribute('lastname'),
datetime: nodes[i].getAttribute('datetime'),
content: nodes[i].childNodes[0].nodeValue
});
}
console.log(comments);
I don't have time to post a full code sample, but JS supports XPath and you can get the Comments with this Qpath query:
/FRIENDSSTATUS/STATUSFRIENDS[#id="3"]/COMMENTS
Here is where I tested the Xpath syntax: http://chris.photobooks.com/xml/default.htm

JQGrid MultiSelect getting the column data

Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}

Categories