I'm using the following code to make a call to a REST API using JavaScript. This code works fine with IE but hangs at send method with Firefox 9.0.1. I believe IE is not cashing the previous response.
I have tried debugging with Firebug, but it's not helping. XMLHttpRequest object, which is for Firefox, is created successfully and it goes through all the code, but no response.
<script language="javascript" type="text/javascript">
function processRequest() {
var signedURI = "http://api.saaspose.com/v1.0/storage/disc?appSID=myappSID&signature=mySignature";
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
if (typeof xmlhttp.overrideMimeType != 'undefined') {
xmlhttp.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Not supported!');
}
xmlhttp.open('GET', signedURI, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else {
//alert("ready state : " + xmlhttp.readyState.toString() + " status : " + xmlhttp.status.toString());
}
};
xmlhttp.send(null);
}
</script>
Any idea why is this issue occurring with Firefox but not with IE?
The team had to resolve this issue by adding JSONP support to the WCF services and then using the jQuery at the client end like this:
$(function () {
$("#disc").click(function () {
$.getJSON("http://api.saaspose.com/v1.0/storage/disc?appSID=appsid&signature=signature&callback=?", function (data) {
var items = [];
$("#discResult").append('<br/><b>Status: ' + data.Status + '</b>');
if (data.Status = 'OK') {
var discUsage = data.DiscUsage;
$.each(discUsage, function (key, val) {
items.push('<li id="' + key + '">' + key + ': ' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#discResult');
}
});
});
});
Thank you all for your comments.
Related
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>
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;
i've been tasked create a xhr post request to websocket server,
however whenever chrome is used, it returns net::ERR_CONNECTION_RESET 50% of the time.
this does not occurs on other browser as tested on safari, firefox, and microsoft edge.
function doPost(url, data) {
promisePost(url, data)
.then(
function (val) {
console.log("returns: " + val);
}, function (error) {
console.log("error: " + error);
})
};
var promisePost = function (url, data) {
return new Promise(function (resolve, reject) {
try {
var xhr = new XMLHttpRequest();
xhr.upload.onabort = function () {
reject("aborted by user");
};
xhr.timeout = 5000;
xhr.ontimeout = function () {
reject("error#timeout");
};
var handleStateChange = function () {
switch (xhr.readyState) {
case 4:
//responses
if (xhr.status == 0) {
//undefined error it return xhrstatus 0
reject("error#xhrcode:" + xhr.status);
} else {
if (xhr.responseText == "") {
reject("error#response is empty");
} else
resolve("done#xhrcode:" + xhr.status + "#responses:" + xhr.responseText);
}
break;
default:
//error with statuscode
reject("error#xhrcode:" + xhr.status + "#responses:" + xhr.responseText);
};
};
xhr.onerror = function (e) {
reject("status code: " + xhr.status + " " + e);
};
xhr.onreadystatechange = handleStateChange;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
} catch (e) {
//error in script
reject("scerror " + e.message);
}})
};
i'm 100% certain that the server already have cors support since i've been testing it via other browser.
anyone got any idea how to solve this? been stuck on this for past 3 weeks
I have a script that allows the user to view locations of comms cabinets. I am trying to get html5 to pass latitude and longitude to a php script(geo.php) to update the record in the database with the map coordinates, but keep getting errors:
ReferenceError: Can't find variable: pos
this is my code. Please help me get the latitude and longitude to appear in the link to be called by ajax:
function getLocation() {
navigator.geolocation.getCurrentPosition(function(pos)
{
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
});
}
function saveLocation(building, commNo) {
getLocation();
var latitude = lat;
var longitude = lng;
alert(latitude + longitude);
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The geolocation API is asynchronous, just like your ajax call, so you have to wait for the results to return, and even if you did have to wait for the async call, variables are only available inside the scope where they are defined.
function getLocation(callback) {
navigator.geolocation.getCurrentPosition(function (pos) {
callback(pos.coords.latitude, pos.coords.longitude);
});
}
function saveLocation(building, commNo) {
getLocation(function(latitude, longitude) {
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
});
}
Goal : When click a link on my navigation will show spinning image until script fully loaded.
function ahah(url, target) {
document.getElementById(target).innerHTML = '<img src="loading.gif" />';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
On Link
File 1
File 2
On content wrapper
<div id="content"></div>
Let me know simple way to do this on jquery.
Assuming each <a href="wrapper.html"> element corresponds sequentially to a file-n.html, you could do this:
$(function() {
var content = $('#content');
$('a[href="wrapper.html"]').each(function( i ) {
var name = "file" + (i + 1) + '.html';
$(this).click(function( e ) {
e.preventDefault();
content.html( '<img src="loading.gif" />' );
$.ajax({
url: name,
dataType: 'html',
success: function( data ) {
content.html( data );
},
error: function(xhr, status, error) {
content.html( "Error:\n" + status + "\n" + error;
}
});
});
});
});
Of course, don't forget to include the jQuery library first.
I think you only need to rewrite 'ahah'. Here is how I did it. I also omitted your 'ahahDone' callback and incorporated it into this implementation.`
function ahah(url, target) {
$("#" + target).html('<img src="loading.gif" />');
$.ajax({
url: url,
type: "GET",
success: function (data, status, req) { $("#" + target).text(req.responseText); },
error: function (req, status, err) { $("#" + target).text(" AHAH Error:\n" + req.status + "\n" + req.statusText); }
});
}