This is probably a very simple oversight on my behalf, but I cannot get the below to run.
I am triggering this function at the press of a button in a form element. If I run this outside of the getData() function it works correctly (with a manually coded URL), but trying to run the function does not work.
Could someone please take a look at this and advise where I may be going wrong?
function getData(form) {
var url = '/service/search/' + form.date.value;
var getStats = new XMLHttpRequest();
getStats.open('GET', url, true);
getStats.onload = function() {
if (getStats.status = 200) {
//Add JSON to "data"
var data = JSON.parse(getStats.responseText);
var list = '';
if (data.length > 0) {
document.getElementById('results').innerHTML += '<tr><th> </th><th>Start</th><th>End</th><th>Title</th><th> </th></tr>'
}
for (var i = 0; i < data.length; i++) {
list += '<tr data-state="'+data[i].state+'" class="'+data[i].type+'-item"><td class="crm-'+data[i].state+'"></td><td>'+data[i].start+'</td><td>'+data[i].end+'</td><td>'+data[i].title+'</td><td>View</td>';
}
//document.getElementById('results').innerHTML += list;
console.log(list);
} else {
console.error('HTTP ERROR: ' + getStats.status);
}
};
getStats.onerror = function() {
console.error('ERROR');
};
getStats.send();
}
UPDATE
As requested, this is how I am calling the function:
<form onsubmit="getData(this);">
<input type="text" placeholder="YYYY-MM-DD" id="date">
<input type="submit" value="Search">
</form>
In regards to when this works correctly, if I run the below outside of a function it works:
var url = '/service/search/2014-06-11';
var getStats = new XMLHttpRequest();
getStats.open('GET', url, true);
getStats.onload = function() {
if (getStats.status = 200) {
//Add JSON to "data"
var data = JSON.parse(getStats.responseText);
var list = '';
if (data.length > 0) {
document.getElementById('results').innerHTML += '<tr><th> </th><th>Start</th><th>End</th><th>Title</th><th> </th></tr>'
}
for (var i = 0; i < data.length; i++) {
list += '<tr data-state="'+data[i].state+'" class="'+data[i].type+'-item"><td class="crm-'+data[i].state+'"></td><td>'+data[i].start+'</td><td>'+data[i].end+'</td><td>'+data[i].title+'</td><td>View</td>';
}
//document.getElementById('results').innerHTML += list;
console.log(list);
} else {
console.error('HTTP ERROR: ' + getStats.status);
}
};
getStats.onerror = function() {
console.error('ERROR');
};
getStats.send();
Related
I'm trying to do a client-side database visualizer with JS. I have never used JavaScript for doing this type of stuff, so I searched online and I found out this web page. This is the script that I have done.
<html>
<head>
<script>
function handleFiles(files)
{
var file = files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
openSqliteDb(reader);
}
function openSqliteDb(reader)
{
setTimeout(function () {
if(reader.readyState == reader.DONE)
{
var database = SQL.open(bin2Array(reader.result));
document.write("2");
executeQuery("SELECT * FROM User", database);
}
else
{
openSqliteDb(reader);
}
}, 500);
}
function executeQuery(commands, database)
{
document.write("1");
commands = commands.replace(/n/g, '; ');
try {
var data = database.exec(commands);
document.write(data);
processData(data);
} catch(e) {
console.log(e);
}
}
function processData(data)
{
document.write("1");
var colHeaders = [];
var colMap = {};
var tableContent = [];
var tableHtml = [];
tableHtml.push("<table border='1' cellspacing='2' cellpadding-'3'>");
for (var i = 0; i < data.length; i++) {
tableContent.push("<tr>");
var dataElem = data[i];
if (dataElem instanceof Array) {
for (var j = 0; j < dataElem.length; j++) {
var element = dataElem[j];
if (element.column && !colMap[element.column]) {
colHeaders.push("<th>" + element.column + "</th>");
colMap[element.column] = colHeaders.length;
tableContent.push("<td> " + element.value + "</td>");
} else {
tableContent.push("<td> " + element.value + "</td>");
}
}
} else {
if (element.column && !colMap[element.column]) {
colHeaders.push(element.column);
colMap[element.column] = colHeaders.length;
}
}
tableContent.push("</tr>");
}
tableHtml.push(colHeaders.join(" "));
tableHtml.push(tableContent.join(" "));
tableHtml.push("</table>");
document.getElementById("table").innerHTML = tableHtml.join(" ");
}
</script>
</head>
<body>
<input type="file" id="input" onchange="handleFiles(this.files)">
</body>
</html>
I can't figure it out why it is not working, but I think that the problem is the line var database = SQL.open(bin2Array(reader.result)); in the openSqliteDb() function. Can somebody help me?
I'm binding data to 3 dropdowns by calling a method from another file of javascript. The data source of dropdown loading from IndexedDB.
Data binding JS,
function bindStateData(){
getMstStates("#state");
getMstStates("#drstate");
getMstStates("#cstate");
}
Database manager js,
function getMstStates(state) {
var request = indexedDB.open('AppDatabase', '3')
request.onsuccess = function (e) {
var dbInstance = e.target.result;
let transaction = dbInstance.transaction("MstStates", "readonly");
const statesDetailsStore = transaction.objectStore("MstStates");
stateData = statesDetailsStore.getAll();
stateData.onsuccess = function () {
var MstStatesMap = new Object();
var len = stateData.result.length,
i;
for (i = 0; i < len; i++) {
MstStatesMap[i] = {};
MstStatesMap[i].StateId = stateData.result[i].StateId;
MstStatesMap[i].StateName = stateData.result[i].StateName;
}
callBackOptionItems(MstStatesMap, state);
}
stateData.onerror = function () {
console.log('getMstStates : ' + e);
}
}
request.onerror = function (e) { console.log('getMstStates : ' + e); }
}
function callBackOptionItems(MstOptionMap, objID) {
for (var j in MstOptionMap) {
var k, v
var tem = 0;
for (var i in MstOptionMap[j]) {
if (tem == 0) {
k = MstOptionMap[j][i]
} else {
v = MstOptionMap[j][i];
}
tem++
}
var el = $(objID);
$(el).append('<option value="' + k + '">' + v + '</option>');
}
if (objID == '#select-history') {
$("#select-history").append('<option value="4">Other</option>');
}
}
When I tried to loading data I got the following error,
Uncaught DOMException: Failed to read the 'result' property from 'IDBRequest': The request has not finished.
at IDBRequest.stateData.onsuccess
The same code logic was written in WebSQL, it was running properly, but unfortunately from iOS 13 version websql support has been revoked.
I have resolved this issue. The main culprit line is,
var len = stateData.result.length;
The correct code is as follows,
var _request = statesDetailsStore.getAll();
_request.onsuccess = function (event) {
var MstStatesMap = new Object();
var stateData = event.target.result;
}
As others before I used yql to get data from a website. The website is in xml format.
I am doing this to build a web data connector in Tableau to connect to xmldata and I got my code from here: https://github.com/tableau/webdataconnector/blob/v1.1.0/Examples/xmlConnector.html
As recommended on here: YQL: html table is no longer supported I tried htmlstring and added the reference to the community environment.
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
However, I still got the message: Html table no longer supported.
As I don't know much about yql, I tried to work with xmlHttpRequestinstead, but Tableau ended up processing the request for ages and nothing happened.
Here my attempt to find another solution and avoid the yql thingy:
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//INSTEAD OF THIS:
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//USE NOT YQL BUT XMLHTTPREQUEST:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
Does anyone have an idea how to get YQL work or comment on my approach trying to avoid it?
Thank you very much!
For reference, if there is any Tableau user that wants to test it on Tableau, here is my full code:
<html>
<head>
<title>XML Connector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
var myConnector = tableau.makeConnector();
myConnector.init = function () {
tableau.connectionName = 'XML data';
tableau.initCallback();
};
myConnector.getColumnHeaders = function() {
_retrieveXmlData(function (tableData) {
var headers = tableData.headers;
var fieldNames = [];
var fieldTypes = [];
for (var fieldName in headers) {
if (headers.hasOwnProperty(fieldName)) {
fieldNames.push(fieldName);
fieldTypes.push(headers[fieldName]);
}
}
tableau.headersCallback(fieldNames, fieldTypes); // tell tableau about the fields and their types
});
}
myConnector.getTableData = function (lastRecordToken) {
_retrieveXmlData(function (tableData) {
var rowData = tableData.rowData;
tableau.dataCallback(rowData, rowData.length.toString(), false);
});
};
tableau.registerConnector(myConnector);
})();
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//here try another approach not using yql but xmlHttpRequest?
//try xml dom to get url (xml http request)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
window.cachedTableData = _xmlToTable(xmlDoc);
}
// There are a lot of ways to handle URLS. Sometimes we'll need workarounds for CORS. These
// methods chain together a series of attempts to get the data at the given url
function _ajaxRequestHelper(url, successCallback, conUrl, nextFunction,
specialSuccessCallback){
specialSuccessCallback = specialSuccessCallback || successCallback;
var xhr = $.ajax({
url: conUrl,
dataType: 'xml',
success: specialSuccessCallback,
error: function()
{
nextFunction(url, successCallback);
}
});
}
// try the straightforward request
function _basicAjaxRequest1(url, successCallback){
_ajaxRequestHelper(url, successCallback, url, _yqlProxyAjaxRequest2);
}
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
// Takes a hierarchical xml document and tries to turn it into a table
// Returns an object with headers and the row level data
function _xmlToTable(xmlDocument) {
var rowData = _flattenData(xmlDocument);
var headers = _extractHeaders(rowData);
return {"headers":headers, "rowData":rowData};
}
// Given an object:
// - finds the longest array in the xml
// - flattens each element in that array so it is a single element with many properties
// If there is no array that is a descendent of the original object, this wraps
function _flattenData(xmlDocument) {
// first find the longest array
var longestArray = _findLongestArray(xmlDocument, xmlDocument);
if (!longestArray || longestArray.length == 0) {
// if no array found, just wrap the entire object blob in an array
longestArray = [objectBlob];
}
toRet = [];
for (var ii = 0; ii < longestArray.childNodes.length; ++ii) {
toRet[ii] = _flattenObject(longestArray.childNodes[ii]);
}
return toRet;
}
// Given an element with hierarchical properties, flattens it so all the properties
// sit on the base element.
function _flattenObject(xmlElt) {
var toRet = {};
if (xmlElt.attributes) {
for (var attributeNum = 0; attributeNum < xmlElt.attributes.length; ++attributeNum) {
var attribute = xmlElt.attributes[attributeNum];
toRet[attribute.nodeName] = attribute.nodeValue;
}
}
var children = xmlElt.childNodes;
if (!children || !children.length) {
if (xmlElt.textContent) {
toRet.text = xmlElt.textContent.trim();
}
} else {
for (var childNum = 0; childNum < children.length; ++childNum) {
var child = xmlElt.childNodes[childNum];
var childName = child.nodeName;
var subObj = _flattenObject(child);
for (var k in subObj) {
if (subObj.hasOwnProperty(k)) {
toRet[childName + '_' + k] = subObj[k];
}
}
}
}
return toRet;
}
// Finds the longest array that is a descendent of the given object
function _findLongestArray(xmlElement, bestSoFar) {
var children = xmlElement.childNodes;
if (children && children.length) {
if (children.length > bestSoFar.childNodes.length) {
bestSoFar = xmlElement;
}
for (var childNum in children) {
var subBest = _findLongestArray(children[childNum], bestSoFar);
if (subBest.childNodes.length > bestSoFar.childNodes.length) {
bestSoFar = subBest;
}
}
}
return bestSoFar;
}
// Given an array of js objects, returns a map from data column name to data type
function _extractHeaders(rowData) {
var toRet = {};
for (var row = 0; row < rowData.length; ++row) {
var rowLine = rowData[row];
for (var key in rowLine) {
if (rowLine.hasOwnProperty(key)) {
if (!(key in toRet)) {
toRet[key] = _determineType(rowLine[key]);
}
}
}
}
return toRet;
}
// Given a primitive, tries to make a guess at the data type of the input
function _determineType(primitive) {
// possible types: 'float', 'date', 'datetime', 'bool', 'string', 'int'
if (parseInt(primitive) == primitive) return 'int';
if (parseFloat(primitive) == primitive) return 'float';
if (isFinite(new Date(primitive).getTime())) return 'datetime';
return 'string';
}
function _submitXMLToTableau(xmlString, xmlUrl) {
var conData = {"xmlString" : xmlString, "xmlUrl": xmlUrl};
tableau.connectionData = JSON.stringify(conData);
tableau.submit();
}
function _buildConnectionUrl(url) {
// var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
// var query = "select * from html where url='" + url + "'";
// var restOfQueryString = "&format=xml";
// var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString;
// return yqlUrl;
return url;
}
$(document).ready(function(){
var cancel = function (e) {
e.stopPropagation();
e.preventDefault();
}
$("#inputForm").submit(function(e) { // This event fires when a button is clicked
// Since we use a form for input, make sure to stop the default form behavior
cancel(e);
var xmlString = $('textarea[name=xmlText]')[0].value.trim();
var xmlUrl = $('input[name=xmlUrl]')[0].value.trim();
_submitXMLToTableau(xmlString, xmlUrl);
});
var ddHandler = $("#dragandrophandler");
ddHandler.on('dragenter', function (e)
{
cancel(e);
$(this).css('border', '2px solid #0B85A1');
}).on('dragover', cancel)
.on('drop', function (e)
{
$(this).css('border', '2px dashed #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) { _submitXMLToTableau(reader.result); };
reader.readAsText(file);
});
$(document).on('dragenter', cancel)
.on('drop', cancel)
.on('dragover', function (e)
{
cancel(e);
ddHandler.css('border', '2px dashed #0B85A1');
});
});
</script>
<style>
#dragandrophandler {
border:1px dashed #999;
width:300px;
color:#333;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin:10px;
font-size:150%;
}
</style>
</head>
<body>
<form id="inputForm" action="">
Enter a URL for XML data:
<input type="text" name="xmlUrl" size="50" />
<br>
<div id="dragandrophandler">Or Drag & Drop Files Here</div>
<br>
Or paste XML data below
<br>
<textarea name="xmlText" rows="10" cols="70"/></textarea>
<input type="submit" value="Submit">
</form>
I have trouble in parsing the JSON using the Javascript.My resultant variable 'text' do does not have the result after completion of loop. Can anybody guide me how can I parse this JSON properly.
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var i = 0; i <= data.length; i++) {
text += '<option>' + data[i].member_first_name + '</option>';
}
console.log(text); // here not get result in text
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();
also content of data.json are
[
{"member_id":"3","member_first_name":"sachin ","member_last_name":"kumar"},
{"member_id":"4","member_first_name":"abhijit","member_last_name":"kumar"},
{"member_id":"5","member_first_name":"nithin","member_last_name":"ev"},
{"member_id":"6","member_first_name":"tukaram","member_last_name":"kumar"},
{"member_id":"7","member_first_name":"manish","member_last_name":"mungle"},
{"member_id":"8","member_first_name":"dsfdgfh","member_last_name":"dfgfhgfh"},
{"member_id":"9","member_first_name":"hjhgjkhkhj","member_last_name":""},
{"member_id":"10","member_first_name":"hjhkjhggf","member_last_name":""},
{"member_id":"11","member_first_name":"klkjlgfhf","member_last_name":"hjghkj"},
{"member_id":"12","member_first_name":"jkhkjhkl","member_last_name":"hgjgffhfkhj"},
{"member_id":"13","member_first_name":"hfgtjgjhg","member_last_name":"fghjgfhjg"},
{"member_id":"14","member_first_name":"hgjgfjhj","member_last_name":"hgjhgjhfg"},
{"member_id":"15","member_first_name":"cvcxvnvnbv","member_last_name":"nbvcbvc"},
{"member_id":"16","member_first_name":"vbvcnbnbm","member_last_name":"vbxgdssdg"},
{"member_id":"17","member_first_name":"lkfndbfbsd","member_last_name":"dfggfhfh"},
{"member_id":"18","member_first_name":"fghjjdfd","member_last_name":"fgfghghf"},
{"member_id":"19","member_first_name":"ghgfjhfj","member_last_name":"fghfhfd"},
{"member_id":"20","member_first_name":"dfhgfhh","member_last_name":"gdfhfd"}
]
To traverse the object array best available in java script that , traverse the object array using for/in loop than for loop, so my final code which traverse the object array as follow:-
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var key in data) {
text += '<option>' + data[key].member_first_name + '</option>';
}
console.log(text);
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();
I posted earlier regarding a different topic and want to thank all who helped me out. I've cleaned up my code pretty well (I think) but now when I click 'submit' nothing happens. I suspect the issue is regarding sending data with ajax but there is a problem with the way I've written things to send both text and radio data. Before posting this, I did do a thorough search to see if the question may have been answered in another's post but didn't find it - probably because I'm not astute enough with javascript to relate it to my own code. Anyway, here is a sample http://jsfiddle.net/J2yWQ/78/ If someone could find my issue I would really appreciate it.
function emailWarning() {
var check = document.getElementById("check");
check.className = 'show';
}
function validateEmail(xem) {
var re = /\S+#\S+\.\S+/;
return re.test(xem);
}
function postData() {
email = 'email'+document.getElementById('email').value;
var tt = validateEmail(email);
if (tt == true) {
xmlhttp.open('POST', 'payment.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(myProps.join("&"));
} else {
emailWarning();
}
}
var myProps = [];
function insert() {
try {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
myProps = [];
function addProp(id) {
var input = document.getElementById(id);
if(!input) {
input = document.forms[0][id];
}
var value = encodeURIComponent(input.value);
myProps.push(id + "=" + value);
}
addProp('child_name');
addProp('age');
addProp('hometown');
addProp('boy_girl');
addProp('first_name');
addProp('last_name');
addProp('email');
addProp('address1');
addProp('address2');
addProp('city');
addProp('state');
addProp('zip');
addProp('country');
var flagInvalid = false;
var tempArray = document.getElementsByClassName("required");
for (var i = 0; i < tempArray.length; i++) {
if (tempArray[i].value == "") {
flagInvalid = true;
break;
}
}
if (flagInvalid == false) {
postData();
} else {
var showValidationError = function(id) {
var el = document.getElementById(id);
if (el) {
el.className = 'show';
}
else {
alert('Missing element #' + id);
}
}
showValidationError('log');
for (var i = 1; i < 12; i++) {
showValidationError('log' + i);
}
}
} catch (e) {
alert('An error occured in inert: ' + e);
}
}