I have this code from w3school and modified it to suit my need and I come up with this code
<div id="city"></div>
<p id="demo"></p>
<div id="province"></div>
<script>
(function () {
var xmlhttp = new XMLHttpRequest();
var url = "http://getpark.net/city/read";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<div class='row'>" +
"<div class='large-12 columns'>" +
"<label>City</label>" +
"<select id='select' name='city' onchange='change()'>";
for(i = 0; i < arr.length; i++) {
out += "<option value='" +
arr[i].cityId +
"'>" +
arr[i].cityName +
"</option>";
}
out += "</select>" +
"</div>" +
"</div>";
document.getElementById("city").innerHTML = out;
}
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
})();
but why that onchange in change() function didn't work out? I see it from w3school.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange
thank you.
Your change-function should be in the global scope. You only have to move the declaration of the function directly after the script-tag.
<script>
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
(function () {
[..]
Related
First of all,
you can see below, my working program to fetch Data from two different APIs in two different tables.
First table contains the data from an API : {Cycle, Delegated Stack, Share, expected payment}
The second one gets the data from another API to get : {the cycle, paid reward}
https://codepen.io/alexand92162579/pen/arJqmv?editors=1010
The second Code pen is the same thing but I want to merge the two tables according to the value of the cycle:
https://codepen.io/alexand92162579/pen/OGdjLJ?editors=1011
According to what I read online, I need to use Promises. I have tried this multiple times but never succeeded to make it work !
To try it, enter the Key KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 in the inputbox.
I will make a donation of 30xtz if someone helps me on this one.
// Fonction to fetch the data for every cycle on the first API
// Data Recolted (Cycle, Balance, Share, Expected Reward, Fee, Status)
// Try to merge with the second table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 */
function calculate2() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
console.log(KT1);
xmlhttp.onreadystatechange = function() {
Qfee = 0.08;
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
txt += "<th>Cycle</th>"
txt += "<th>Balance</th>"
txt += "<th>Share</th>"
txt += "<th>Reward</th>"
txt += "<th>Fee</th>"
txt += "<th>Status</th>"
txt += "</tr>"
for (x in myObj) {
cycle = myObj[x].cycle;
balance = myObj[x].balance/1000000;
TotalReward = myObj[x].rewards/1000000;
status = myObj[x].status.status;
stakingBalance = myObj[x].staking_balance/1000000;
Share = balance/stakingBalance*100;
Fee = Share*TotalReward*Qfee/100;
DelegatorReward = Share*TotalReward/100 - Fee;
txt += "<tr>";
txt += "<td width=10% align=center>" + cycle + "</td>";
txt += "<td width=25% align=center>" + Math.round(balance*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Share*10)/10 + " %" + "</td>";
txt += "<td width=10% align=center>" + Math.round(DelegatorReward*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Qfee*1000)/10 + " %" + "</td>";
txt += "<td width=30% align=left>" + status + "</td>";
txt += "</tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
/*Fonction to fetch the data for every cycle on the second API
// Data Recolted (Cycle, Payment)
// Try to merge with the first table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54*/
function calculate3() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
//console.log(KT1);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
//txt += "<th>Block</th>"
txt += "<th>Cycle</th>"
txt += "<th>Paid</th>"
txt += "</tr>"
//If one transaction has been done for the cycle get from the API request 1 then I put the data on the last column of the table
for (var x = 0; x < 30; x++) {
if (KT1 == myObj[x].type.operations[0].destination.tz) {
console.log("Get one");
Block = myObj[x].type.operations[0].op_level;
console.log(Block);
PaiementCycle = Math.round(Block/4096);
PaiementCycle = PaiementCycle - 6;
console.log(PaiementCycle);
Paid = myObj[x].type.operations[0].amount/1000000;
console.log(Paid);
txt += "<tr>";
//txt += "<td width=10% align=center>" + Block + "</td>";
txt += "<td width=10% align=center>" + PaiementCycle + "</td>";
txt += "<td width=25% align=center>" + Paid + "</td>";
txt += "</tr>";
console.log(txt);
} else {
//console.log("Next");
}
}
txt += "</table>";
document.getElementById("demo2").innerHTML = txt;
return txt;
console.log("ici :" + xmlhttp);
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
$(function () {
/*when #tezos input loses focus, as per original question*/
$('#KT1').blur(function () {
calculate3();
calculate2();
console.log(back)
});
$('#KT1').change(function () {
calculate3();
calculate2();
});
$('#KT1').on(function () {
calculate3();
calculate2();
});
$('#KT1').keyup(function () {
calculate3();
calculate2();
});
$('#KT1').keydown(function () {
calculate3();
calculate2();
});
});
</script>
not tested - but i think it might help - i also tried to reduce function sizes for readability ;)
function getAndLogKT1(){
var KT1 = document.querySelector('#KT1')
console.log(KT1 && KT1.textContent)
return KT1 && KT1.textContent
}
function firstApiReadystatechange(){
}
function createTable(){
return document.createElement('table');
}
function addTableHeader(table, keys){
var thead = document.createElement('thead');
var tr = document.createElement('tr');
for(var i = 0; i < keys.length; i++){
var th = document.createElement('th')
var text = document.createTextNode(keys[i])
th.appendChild(text)
tr.appendChild(th)
}
thead.appendChild(tr)
table.appendChild(thead)
}
function addRowToTableBody(table, rowItems){
var body = table.querySelector('tbody')
if(!body){
body = document.createElement('tbody')
table.appendChild(body)
}
var tr = document.createElement('tr')
for(var i = 0; i < rowItems.length; i++){
var td = document.createElement('td')
var text = document.createTextNode(rowItems[i])
td.appendChild(text)
tr.appendChild(td)
}
body.appendChild(tr)
}
function getDbParam(dbParmaObj){
return JSON.stringify(dbParmaObj)
}
function sendRequestFirstApi(xmlhttp, KT1, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnFirstApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestFirstApi(xmlhttp, getAndLogKT1(), getDbParam({table: "cycle", limit: 10}))
})
}
function sendRequestSecondApi(xmlhttp, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnSecondApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestSecondApi(xmlhttp, getDbParam({table: "cycle", limit: 10}))
})
}
function parseObjectCycleHashed(respObject){
var retObj = {}
for(var x in respObject){
retObj[respObject[x]['cycle']] = respObject[x]
}
return retObj
}
function mergeCycleHashedResponseObjects(a,b){
let cyclesA = Object.keys(a)
var retObj = Object.assign({}, b)
for(var i = 0; i < cyclesA.length; i++){
Object.assign(retObj, {[cyclesA[i]]: a[cyclesA[i]] })
}
return retObj
}
function addToDOM(element, querySelector){
var el = document.querySelector(querySelector)
el && el.appendChild(element)
}
async function main(){
var responseObjApiOne = await fetchDataForEveryCycleOnFirstApi();
var responseObjApiTwo = await fetchDataForEveryCycleOnSecondApi();
var responseObjApiOneCycleBased = parseObjectCycleHashed(responseObjApiOne);
var responseObjApiTowCycleBased = parseObjectCycleHashed(responseObjApiTwo);
var mergedObject = mergeCycleHashedResponseObjects(responseObjApiOneCycleBased, responseObjApiTowCycleBased)
var table = createTable()
const headerKeys = [
"Cycle",
"Balance",
"Share",
"Reward",
"Fee",
"Status",
"Paid"
]
addTableHeader(table, headerKeys)
for(var cycle in mergedObject){
addRowToTableBody(table, headerKeys.map(columnTitle => {
return mergedObject[cycle][columnTitle]
}))
}
addToDOM(table, "dmeo2")
}
The Sting "Fahrzeugnummer" in "Fahrten: All other strings in "Fahrten" are working fine. Just "Fahrzeugnummer" can't be displayed.
Table
<table style="width:100%" id="fahrten-tabelle"></table>
Script
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "https://start.vag.de/dm/api/v1/fahrten.xml/Bus?timespan=100", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
//Problem:
var fznr = x[i].getElementsByTagName("Fahrzeugnummer")[0] ? x[i].getElementsByTagName("Fahrzeugnummer")[0].childNodes[0].nodeValue : "";
table += "<tr><td>" +
//Problem:
fznr +
"</td><td>" +
x[i].getElementsByTagName("Linienname")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
</script>
Thanks.
To get the value use innerHTML and not nodeValue.
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].childNodes[0].innerHTML + "</td><td>" + x[i].childNodes[1].innerHTML + "</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
here's a demo
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "https://start.vag.de/dm/api/v1/fahrten.xml/Bus?timespan=100", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].childNodes[0].innerHTML + "</td><td>" + x[i].childNodes[1].innerHTML + "</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
<body onload="loadXMLDoc()">
<table style="width:100%" id="fahrten-tabelle"></table>
</body>
I have two different codes for two different URL to fetch data. Code is as below :
Code 1 :
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
vosRequest.accounts = new Array(1);
vosRequest.accounts[0] = new Object();
vosRequest.accounts[0] = document.getElementById("accounts").value;
xmlHttp.open("POST", "http://..../GetCustomer", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var json = JSON.parse(xmlHttp.responseText);
document.getElementById('id01').innerHTML = json.infoCustomers[0].infoCustomerAdditional.linkMan;
document.getElementById('id02').innerHTML = json.infoCustomers[0].account;
document.getElementById('id03').innerHTML = json.infoCustomers[0].name;
var num = json.infoCustomers[0].money;
var n = num.toFixed(3);
document.getElementById('id04').innerHTML = n;
var d = new Date(json.infoCustomers[0].validTime);
d = d.toGMTString();
document.getElementById('id05').innerHTML = d;
}
}
}
</script>
Code 2:
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
if(document.getElementById("checkbox_account").checked){
vosRequest.account = document.getElementById("account").value;
}
if(document.getElementById("checkbox_areaCode").checked){
vosRequest.areaCode = document.getElementById("areaCode").value;
}
if(document.getElementById("checkbox_period").checked){
vosRequest.period = parseFloat(document.getElementById("period").value);
}
if(document.getElementById("checkbox_beginTime").checked){
vosRequest.beginTime = document.getElementById("beginTime").value;
}
if(document.getElementById("checkbox_endTime").checked){
vosRequest.endTime = document.getElementById("endTime").value;
}
xmlHttp.open("POST", "http://.../GetReportCustomerLocationFee", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var obj, dbParam, xmlhttp, myObj, x, txt = "";
var json = JSON.parse(xmlHttp.responseText);
//txt += ""
for (x=0;x<json.infoReportCustomerLocationFees.length;x++) {
txt += "<tr><td>" + json.infoReportCustomerLocationFees[x].areaCode + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].areaName + "</td>";
json.infoReportCustomerLocationFees[x].totalFee = json.infoReportCustomerLocationFees[x].totalFee.toFixed(3);
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalTime + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFeeTime + "</tr></td>";
}
// txt += "</table>"
document.getElementById("demo1").innerHTML = txt;
}
}
}
function load(){
document.getElementById("account").value = "ABC";
document.getElementById("areaCode").value = "1";
document.getElementById("period").value = "7";
document.getElementById("beginTime").value = "20170828";
document.getElementById("endTime").value = "20170903";
}
</script>
Both the codes are in two different html files and as an individual, both runs fine and fetches data.
I want to fetch the data of both the url in one html, i.e. I want to merge both the files and retreive data of both the request in single HTML file.
Can u suggest how can i do it? I have searched on stackoverflow but not able to find the right solution.
Thanks in advance.
I have been following an online tutorial to autocomplete textboxes with database values after the user enters a code greater than 7 characters. I have completed most of what I am trying to achieve however I cannot seem to select a value from the combobox to autocomplete the textbox.
I dont have much javascript experience but I am hoping the problem is something small in what I already have, can someone please recommend the change I need to make to select the value from the combobox.
public ActionResult MultiColumnComboBox(string SearchFor, string ControlId)
{
ViewBag.ProcId = SearchFor.Trim();
ViewBag.ControlBlockId = "block" + ControlId.Trim();
ViewBag.ControlId = ControlId.Trim();
ViewBag.ControlTxtId = "txt" + ControlId.Trim();
return View();
}
public JsonResult LoadComboData(string strSearch, string SearchFor)
{
efacsdbEntities db = new efacsdbEntities();
strSearch = strSearch.Trim();
if (SearchFor.Trim() == "employee" && strSearch.Length>7)
{
var res = (from E in db.allpartmasters
where E.partnum.ToLower().Contains(strSearch.ToLower()) || E.partdesc.ToLower().Contains(strSearch.ToLower())
select new
{
E.partnum,
E.partdesc
}).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
<input type="hidden" id="#ViewBag.ProcId" name="#ViewBag.ProcId" value="" />
<input type="hidden" id="#ViewBag.ControlId" name="#ViewBag.ControlId" value="" />
<input type="text" name="#ViewBag.ControlTxtId" id="#ViewBag.ControlTxtId" autocomplete="on" />
<div class="#ViewBag.ControlTxtId renderpart">
<div class="DataBlock">
<div id="#ViewBag.ControlBlockId" style="max-width: 520px;">
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../Scripts/json.debug.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".renderpart").hide();
var txtid = "#" + '#ViewBag.ControlTxtId';
var renderpart = "." + '#ViewBag.ControlTxtId';
var selectlinkvalueid = ".Get" + '#ViewBag.ProcId';
$(selectlinkvalueid).on("click", function () {
var value = $(this).attr('id');
var valueText = $(this).attr('title');
$("##ViewBag.ControlId").val(value);
$(txtid).val(valueText);
$(renderpart).slideUp("slow");
});
$(txtid).keyup(function () {
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var activecols = $("#hdnActiveColumns").val();
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
$(txtid).focusin(function () {
var txtid = "#" + '#ViewBag.ControlTxtId';
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
function CreateDynamicTable(objArray, tempprocId) {
var array = JSON.parse(objArray);
var str = '<table style="width:100%;">';
str += '<tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr>';
str += '<tbody>';
var flag = false;
var ids;
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr>' : '<tr>';
for (var index in array[i]) {
if (flag == false) {
ids = array[i][index];
flag = true;
}
str += '<td><a id="' + ids + '" class="Get' + tempprocId + '" title="' + array[i][index] + '" href="#">' + array[i][index] + '</a></td>';
}
str += '</tr>';
}
str += '</tbody>';
str += '</table>';
return str;
}
});
$(document).click(function (evt) {
var renderpart = "." + '#ViewBag.ControlTxtId';
var theElem = (evt.srcElement) ? evt.srcElement : evt.target;
if (theElem.id == "main" || theElem.id == "sub1") {
$(renderpart).slideUp("fast");
}
});
</script>
Here is the link to the tutorial I was following as well.
Create Multiple column autocomplete combobox
I tried to run this but it doesn't work.
It is intended to return a variable assigned inside a function, that was passed as callback to sendRequest(), which is retrieving data from the Internet through XMLHttpRequest asynchronously.
Can anyone tell me why this is not working and always returning ""?
function sendRequest(requestCode, args, callback){
var req = requestEngineUrl + "?req=" + requestCode + ";" + args;
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
if(callback != null){
callback(xmlHttp.responseText);
}
}
};
xmlHttp.open("GET", req, true);
xmlHttp.send(null);
}
this.assembleProcess = function(){
if(!isNull(this.id) && !isNull(this.titles)){
var titles = this.titles;
var id = this.id;
c = "";
sendRequest('304', id,
function(result){
var res = result.split("/");
var title = res[0];
var possibilities = res[1];
var fcontent = title + '<br><div>';
if(titles.length != possibilities){
console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
}
for(i = 0; i < possibilities; i++){
fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
}
fcontent += '</div>';
c = fcontent;
});
return c;
}
As an XMLHttpRequest is async, you should write an async function for that matter, like this
this.assembleProcess = function(callback){
if(!isNull(this.id) && !isNull(this.titles)){
var titles = this.titles;
var id = this.id;
c = "";
sendRequest('304', id,
function(result){
var res = result.split("/");
var title = res[0];
var possibilities = res[1];
var fcontent = title + '<br><div>';
if(titles.length != possibilities){
console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
}
for(i = 0; i < possibilities; i++){
fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
}
fcontent += '</div>';
c = fcontent;
callback(c)
});
}
and then, instead of using this.assembleProcess as a function with a result, you should pass a function as parameter:
Instead of
console.log(this.assembleProcess);
do this
this.assembleProcess(function(c){console.log(c)});