XMLHTTPRequest not receiving response from LotusScript agent - javascript

I have a LotusScript agent that has the following code at the end
Set nam = session.Createname(respParty)
Print "Content-type: text/plain"
Print nam.Abbreviated
I have a JavaScript button that contains the following prior to a submit()
var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
Everything is working except it is getting back a blank value.
If I put the URL:
http://[webaddress]/[dbname].nsf/GetResponsiblePerson?OpenAgent&NoEmployees=20&State=IL
into the browser exactly as I am passing it into the JS code it returns:
X Content-type: text/plain Susanne Anderson/CBS
What am I doing wrong?
Is my JS code in the wrong order?

var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
}
};
xhttp.send();
Hope this will help.

Related

Passing DB contents from XHTTP request

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>

Parsing data from API, getting undefined

I am new to APIs and I want to add the USDA Nutrients database api to my website. I want the user to be able to search for the food,select one of the appeared results and see its' nutrition information.
How can I do this in plain JS? I've created a search bar in my website and JS takes the input and requests the data from the USDA api.
var apiKey = '';
var q = "eggs";
var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var data = JSON.parse(this.responseText);
document.querySelector("#usdaResults").innerHTML = data.body;
}
};
xhr.send();
I want first to present to the user a list of the results of what they searched. Then after they click the food, I want to present its' nutritional information(protein etc).
EDIT: When a user searches a food, I want to display the "group" , "name"and "manu" of all available results. At the same time,when a user wants to see the nutrition information for a specific food of those listed, I want to get its' "ndbno" number and look into the USDA database for it so I can display the data after. Same way as displayed in the official website: https://ndb.nal.usda.gov/ndb/search/list?SYNCHRONIZER_TOKEN=c91f87b5-59c8-47e0-b7dc-65b3c067b7ff&SYNCHRONIZER_URI=%2Fndb%2Fsearch%2Flist&qt=&qlookup=egg+potato&ds=&manu=
EDIT2: I'm getting this error now.
var apiKey = '';
var q = document.getElementById('search').value;
var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
function getData() {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
var data = JSON.parse(this.responseText);
if (data && data.list && data.list.item) {
var html = "";
data.list.item.map(item => {
let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
html += string;
})
}
document.querySelector("#usdaResults").innerHTML = html;
}
else {
console.log("Error", xhr.statusText);
}
}
xhr.send();
}
HTML:
<section class="usda">
<h1>USDA Nutrients Database</h1>
<form id="search">
<input type="text" placeholder="Search.." name="search">
<button type="button" onclick="getData();">Search</button>
</form>
<div id="usdaResults"></div>
</section>
So, it may be that there are errors with your XHR call - however we can catch and log those errors. You want to open your developer tools in your browser (usually right click > developer tools) to look at the JS logs.
I'm getting: VM131:20 GET http://api.nal.usda.gov/ndb/search/?format=json&q=eggs&sort=n&max=25&offset=0&api_key= 403 (Forbidden)
But that's because I have no API Key. If you do not, you'll need to get an API key from them.
I have grabbed some code from another SO post, here:
var apiKey = '';
var q = "eggs";
var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (oEvent) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
} else {
console.log("Error", xhr.statusText);
}
}
};
xhr.send();
Reference:
XMLHttpRequest (Ajax) Error
EDIT:
For the response, once you have parsed the JSON - you can get all the available name, group and manu of the data as so - I've output the details in tags, and this is untested - so maybe incorrect, but this is more for pseudo code.
var data = JSON.parse(this.responseText);
//Assuming data is valid!
if (data && data.list && data.list.item) {
var html = "";
data.list.item.map(item => {
let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
html += string;
})
}
document.querySelector("#usdaResults").innerHTML = html;

Getting return value from inside [an ajax] function

how do I get the return value of "res" from the function. It shows undefined when i try to access it.
function solution() {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
return res;
}
}
}
You've to use either Promise or callback approach to achieve that. Promise is relatively new and not supported in all browsers.
Promise approach
function solution() {
return new Promise(function(resolve, reject) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var res = this.responseText;
this.status == 200 ? resolve(res) : reject('error');
}
}
});
}
How to get the response
solution().then(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
Callback approach
function solution(success, failure) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var res = this.responseText;
this.status == 200 ? success(res) : error('error');
}
}
}
How to get response
solution(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
You can try this way. Hope its works-
So your XHR function have one callback function to get the return value,
function solution(callback) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh";
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr";
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
callback(res);
}
}
}
when you are calling the XHR function:
solution(function(response){
// you will get the response over here
});

XMLHttpRequest not working while trying to crawl

I am trying to crawl a web page using javascript by making use of api on the click of download button. But I don't receive any responseText in this and same api works using curl.
download.addEventListener('click',function(){
document.getElementById('check').innerHTML = url;
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=json&callback=?';
document.getElementById('check').innerHTML = yql;
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
document.getElementById('check').innerHTML= request.readyState;
if(request.readyState ===XMLHttpRequest.DONE) {
document.getElementById('check').innerHTML= request.responseText;
}
};
request.open("GET", yql, true);
request.send;
},false);
Just remove the callback from the ypl and then this code works fine :
download.addEventListener('click',function(){
document.getElementById('check').innerHTML = url;
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=jsonp';
document.getElementById('check').innerHTML = yql;
var request = new XMLHttpRequest();
request.open("GET", yql, true);
request.send();
request.onreadystatechange = function(){
document.getElementById('check').innerHTML= request.readyState + request.status;
if(request.readyState ===4) {
document.getElementById('check').innerHTML= request.responseText;
}
};
},false);

Why doesn't this ajax function that uses a url work?

In index.html under body tag:
+ -
and under <head><script type="text/javascript">:
var url = "get.php";
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var jsondata = eval("(" + xmlhttp.responseText + ")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function setTempInc()
{
var oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
I don't understand where the problem is. url is a string and jsondata.y is a int but the script doesn't work!
This function does, though:
function setMode(val)
{
var oldUrl = url;
url = url + "91" + val + "000";
ajaxRequest();
url = oldUrl;
}
I would think that
var jsondata = eval("(" + xmlhttp.responseText + ")");
is not available to be called at
url = url + "9001" + jsondata.y;
as it is only defined inside the ajaxRequest function's scope.
Set variables outside functions, to use as a global variable!
This probably will work:
(function() {
var url = "get.php";
var oldUrl = '';
var jsondata = '';
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsondata = eval("("+xmlhttp.responseText+")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function setTempInc()
{
oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
})();
Added Closure to avoid common security problems

Categories

Resources