Passing DB contents from XHTTP request - javascript

I have an xhttp GET request to fetch the items in my db using its api gateway url. The request works fine as I can see my db's contents which are in string (key:value pairs) from the browser's dev console. Where I'm drawing a blank in is how to pass the db's contents to another function that parses it into javascript objects.
Fetch request code
function fetch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "<mygatewayapi_url>", true);
xhttp.send();
}
Code for parsing db contents into javascript object
function displayObj(dataStr){
var obj = JSON.parse(dataStr);
var html = "";
var item =;
//var keys = Object.keys(obj);
//var last = keys[item.length - 1];
for (item in obj){
html += '<li>' + item + ' ' + obj[item] + </li>';
/*if (last === true)
html += '<li>' + item + ' ' + obj[item] + </li>' + "<br>";*/
}
return '<li>'+html+'</li>';

You may handle the result in the xhttp.onreadystatechange callback:
function fetch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var result = displayObj(this.responseText);
console.log("result: \n", result);
document.getElementById("demo").innerHTML = result;
}
};
xhttp.open("GET", "https://api.github.com/emojis", true);
xhttp.send();
}
function displayObj(dataStr){
var obj = JSON.parse(dataStr);
var html = "";
for (var item in obj){
html += '<li>' + item + ' ' + obj[item] + '</li>';
}
return '<ul>'+html+'</ul>';
}
fetch();
<div id="demo"></div>

Related

Want to call multiple XMLHttpRequest base don how much data we have

So I have some Javascript that does an XMLHttpRequest (xhr), on receival of response it does a second response (xhr2) to get remaining data.
But I have now split this second call into batches so that it has to call multiple times depending on how much data there. After the first request I know how many calls I haven to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
But then I am just making multiple calls to xdr2, but this doesn't work because it closes after first call. So I realize I probably need to initialize multiple XMLHttpRequest based on the value of batches, but how do I define the onreadystatechange function succinctly.
function get_tracklist_data(path, cid, title)
{
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
for(i=1; i<batches;i++)
{
xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
xhr2.send();
}
}
};
xhr2.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var data = document.getElementById("tbody");
data.innerHTML+=xhr2.responseText;
}
};
xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
xhr.send();
};
Update to make xhr2 local variable in loop, but doesnt seem to work properly Im getting the same data back multiple times.
function get_tracklist_data(path, cid, title)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
for(i=1; i<batches;i++)
{
var xhr2 = new XMLHttpRequest();
xhr2.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var data = document.getElementById("tbody");
data.innerHTML+=xhr2.responseText;
}
};
xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
xhr2.send();
}
}
};
xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
xhr.send();
};
here example using await fetch() and fetch().then()
function listenForButtonCollapse(buttonId, collapseId, buttonText) {
let button = document.getElementById(buttonId);
let section = document.getElementById(collapseId);
if (section != null) {
section.addEventListener('show.bs.collapse', function() {
button.innerText = 'Hide ' + buttonText;
});
section.addEventListener('hide.bs.collapse', function() {
button.innerText = 'Show ' + buttonText;
});
}
}
async function get_tracklist_data(path, cid, title) {
let xhr = await fetch(path + '?cid=' + cid + "&title=" + title + "&batch=0");
let responseText = await xhr.text()
let counter = document.getElementById("counter");
counter.innerHTML = responseText.substring(0, responseText.indexOf(":"));
let data = document.getElementById("data");
data.innerHTML = responseText.substring(responseText.indexOf(":") + 1);
listenForButtonCollapse('show_focus_button', 'focus_id', 'Spotlight');
listenForButtonCollapse('show_albums_button', 'albums_id', 'Albums');
listenForButtonCollapse('show_tracks_button', 'tracks_id', 'Tracks');
listenForButtonCollapse('show_works_button', 'works_id', 'Works');
//Work out how many calls we need to make
let batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
data = document.getElementById("tbody");
for (i = 1; i < batches; i++) {
fetch(path + '?cid=' + cid + "&title=" + title + "&batch=" + i)
.then(resp => resp.text())
.then(responseText => {
data.innerHTML += responseText;
})
}
}
Using XMLHttpRequest: save xhr object into array then add parameter to the callback listXHR[i].onreadystatechange = function(x) then call x.target for current xhr object
function get_tracklist_data(path, cid, title) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
var listXHR = []
for (i = 1; i < batches; i++) {
listXHR[i] = new XMLHttpRequest();
listXHR[i].onreadystatechange = function(x) {
if (x.target.readyState == 4 && x.target.status == 200) {
var data = document.getElementById("tbody");
data.innerHTML += x.target.responseText;
}
};
listXHR[i].open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=" + i, true);
listXHR[i].send();
}
}
};
xhr.open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=0", true);
xhr.send();
};

onclick() gives error: ReferenceError: LoadAjax is not defined at HTMLInputElement.onclick

Here is my code which does not work at all.
HTML code:
<input type="button" value="Click Here" onclick="LoadAjax()"/>
JS code:
function LoadAjax(){
if (window.XMLHttpRequest) {
request = new XMLHttpRequest()
} else {
request = new ActiveXObject('Microsoft.XMLHTTP')
}
//request.open('GET', 'data.json')
request.open('GET', 'http://localhost:20301/api/values')
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText)
console.log(items);
var output = '<ul>'
for (var key in items) {
console.log(items[key])
output += '<li>' + items[key].Name + ' | ' + items[key].Family + '</li>'
}
output += '</ul>'
document.getElementById('update').innerHTML = output
}
}
request.send()
}
If you have got both in the HTML file, do it this way. It will prevent to call the function before it's loaded by binding the "onClick" after it is loading:
<input type="button" value="Click Here" id="myID">
<script>
function LoadAjax(){
if (window.XMLHttpRequest) {
request = new XMLHttpRequest()
} else {
request = new ActiveXObject('Microsoft.XMLHTTP')
}
//request.open('GET', 'data.json')
request.open('GET', 'http://localhost:20301/api/values')
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText)
console.log(items);
var output = '<ul>'
for (var key in items) {
console.log(items[key])
output += '<li>' + items[key].Name + ' | ' + items[key].Family + '</li>'
}
output += '</ul>'
document.getElementById('update').innerHTML = output
}
}
request.send()
}
myElement = document.getElementById("myID");
myElement.onclick = function() { LoadAjax(); return false; }
</script>
If you have got it in separate files, use this (attention! Inside the js file you DO NOT use the HTML "script" tag.
my.html:
[...]
<input type="button" value="Click Here" id="myID">
[...]
<script src="my.js"></script>
[...]
my.js:
function LoadAjax(){
if (window.XMLHttpRequest) {
request = new XMLHttpRequest()
} else {
request = new ActiveXObject('Microsoft.XMLHTTP')
}
//request.open('GET', 'data.json')
request.open('GET', 'http://localhost:20301/api/values')
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText)
console.log(items);
var output = '<ul>'
for (var key in items) {
console.log(items[key])
output += '<li>' + items[key].Name + ' | ' + items[key].Family + '</li>'
}
output += '</ul>'
document.getElementById('update').innerHTML = output
}
}
request.send()
}
myElement = document.getElementById("myID");
myElement.onclick = function() { LoadAjax(); return false; }

Names are not displaying on the HTML according to JSON Parse

I am trying to display name on the HTML page as list items pulling it from JSON placeholder It is not displaying on the page.
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments');
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.lenght; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
console.log(str);
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
no error display
The only problem I can see in here is the typo of the array items.
Try to change it to length.
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments');
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.length; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
console.log(str);
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
In your code the major problem was that the typo items.length in for loop.
<html>
<div id="data"></div>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments',true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.length; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
</script>
</html>

Check a json value against a regexp throws a is not a function error

I've a problem with an if statement, where I want to check the value against a regExp. But I get "data[key].name is not a function", how do I go about to fix this issue?
document.querySelector('#search').onkeyup = function() {
var searchField = document.querySelector('#search').value;
var myExp = new RegExp(searchField, "i");
var request = new XMLHttpRequest();
request.open('GET', 'allCountries.json', true);
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var data = JSON.parse(request.responseText);
var output = '<ul class="searchresult">';
for(var key in data) {
if(data[key].name(myExp) != -1 || data[key].code(myExp) != -1) {
output += '<li>' + data[key].name + ' - ' + data[key].code +
'</li>';
}
}
output += '</ul>';
document.querySelector('#update').innerHTML = output;
}
};
request.send();
};
If you want to check if a String matches a RegEx pattern, use the String#match() function:
Change your if statement to
if (data[key].name.match(myExp) || data[key].code.match(myExp)) {
var myExp = new RegExp("something.*[23]", "i");
var data = {a:{name:"something1", code:"somethingElse1"}, b:{name:"something2", code:"somethingElse2"}, c:{name:"something3", code:"somethingElse3"}}
var output = '<ul class="searchresult">';
for (var key in data) {
if (data[key].name.match(myExp) || data[key].code.match(myExp)) {
output += '<li>' + data[key].name + ' - ' + data[key].code +
'</li>';
}
}
output += '</ul>';
document.querySelector('#update').innerHTML = output;
<div id="update"></div>
If name and code are strings you should test your regex this way:
if(myExp.test(data[key].name) || myExp.test(data[key].code))

Multiple JSON files in one request from Javascript

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.

Categories

Resources