This is my first post here on Stack. I am trying to make a Get request which is succeeding but I am having trouble getting the responseXML into a variable for processing. I think I am supposed to be using a callback function, but I still can't get it quite right. I am hopeful that somebody can point me in the correct direction. Code below.
<script type="text/javascript">
function buildOptions() {
var data = null;
/*xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
callback.call(xhr.responseXML);
}
});*/ //This code block worked, but I couldn't figure out how to get the result back
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
}
function XMLCallBack(data) {
alert(data); // These two functions were the most recent attempt but I'm still missing something
}
xmlDoc = getXML(XMLCallBack); // this is supposed to start the processing of the returned XML
console.log(xmlDoc);
var campaignName = xmlDoc.getElementsByTagName('self')[0]; //XMLDoc contains a null variable when I get to this line
console.log(campaignName);
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"]; //Code from here and below will be changing slightly once I can get XMLDoc to be correct
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
</script>
I believe you should move open ---> send outside the onreadystatechange, like this:
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
EDIT: This code should work:
<script type="text/javascript">
function buildOptions() {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = XMLCallBack;
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
function XMLCallBack() {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseText;
var campaignName = xmlDoc.getElementsByTagName('self')[0];
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"];
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
}
}
</script>
I haven't tried it so I might have made some mistakes. If you want to, you can move XMLCallBack() outside of buildOptions() and use this.readyState, this.status and this.responseText instead of xhr.readyState etc..
Related
I make APIs all the time and I'm working on one called Swerer. Swerer is an easy and efficient way to use AJAX. Now the problem is when I use Swerer.getFile("file.txt") it returns undefined instead of the content. Any help would be appreciated.
/*
Complex.js 1.0.0
Dec 14, 2017
*/
(function(){
if(!document){
throw new Error("Complex.js needs a window with a document");
}
})();
var toString = Object.prototype.toString;
// Make X
X = function(){
};
X.extend = function(){
var target = arguments[0], obj, arg = arguments;
for (var i = 0; i < arg.length; i++) {
if(toString.call(arg[i]) == "[object Boolean]"){
if(arg[i] !== false){
if(!target){
obj = [];
}else{
for(i in target){
target[i] = obj[i];
}
}
}else{
obj = [];
}
}
}
return obj;
};
// Make constructors
X.extend({
// We are going to make something called Swerer
Swerer: function(){
X.call(this);
},
isFunction: function(obj){
if(toString.call(obj) == "[object Function]"){
return true;
}
},
});
var Swerer = X.Swerer;
Swerer = {};
// Note:
// When we are refering to Swerer in a Swerer function we can use the keyword 'this'
/*
Swerer.get("file.type", function(){
func(arg);
});
*/
// Xhr (XML Http Request) is built into Swerer
(XMLHttpRequest) ? Swerer.xhr = new XMLHttpRequest() : Swerer.xhr = new ActiveXObject("Microsoft.XMLHTTP");
Swerer.getFile = function(file){
var xhttp = this.xhr, content;
if(this.readyState == 4 && this.status == 200){
content = this.responseText;
}
xhttp.open("GET", file, true);
xhttp.send();
return content;
};
If you see any problems post a jsfiddle and I'll try to fix it. Thank you!
I must admit that I only focus on the XHR part of the code, but that should look something like this:
// Xhr (XML Http Request) is built into Swerer
(XMLHttpRequest) ? Swerer.xhr = new XMLHttpRequest() : Swerer.xhr = new ActiveXObject("Microsoft.XMLHTTP");
Swerer.getFile = function(file){
var xhttp = this.xhr;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
return xhttp.responseText;
}
};
xhttp.open("GET", file, true);
xhttp.send();
};
I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.
I have researched this problem, but I still cannot get it to work as it always returns ERROR
The link used is https://www.bitstamp.net/api/ticker/ and the response should be last
Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }
Try this:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonRes= JSON.parse(this.responseText);
if (jsonRes.hasOwnProperty('last')) {
document.getElementById("demo").innerHTML =
jsonRes.last;
alert(jsonRes.last);
}
}
};
xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p>last attribute is: <span id="demo"></span></p>
Here is one way:
<script src="./jquery.min.js">
//none secure web page ?
jQuery.get("https://www.bitstamp.net/api/ticker/", function (data, status)
{
// use response here; jQuery passes it as the first parameter
var response = JSON.parse(data);
window.alert(response.last);
console.log("MyFunc: " + "response : " + response + "\nStatus: " + status);
});
</script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
} else {
window.alert("ERROR");
}
}
}
Why cannot I call variables that I have defined inside a function? This is my code...
var username;
var rank;
var steamid;
var avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
var infoArr = JSON.parse(this.responseText);
var username = infoArr.username;
var rank = infoArr.rank;
var steamid = infoArr.steamid;
var avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}
Function testIt() is returning: undefined
What my code does is to get info from a JSON encoded page and make variables.
If you want to use the variables outside of the function, they need to be defined outside of the function.
var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
infoArr = JSON.parse(this.responseText);
username = infoArr.username;
rank = infoArr.rank;
steamid = infoArr.steamid;
avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}
Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}
I'm using the following code to make multiple async. calls and I need to know how many of those calls are pending for validating purposes.
function llenarComboMetodos(cell) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Las llamandas asincronas no son soportadas por este navegador.");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var combo = '<select name="metodos[]">';
var opciones=xhr.responseText;
combo+= opciones+"</select>";
cell.innerHTML = combo;
}
}
}
xhr.open('POST', 'includes/get_metodos.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("completar=1");
}
Is there a way to know that?
Thank you (:
You can intercept the XMLHttpRequest.send and do your counting of active calls:
var activeXhr = (function(){
var count = 0;
XMLHttpRequest.prototype.nativeSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
this.onreadystatechange = function(){
switch(this.readyState){
case 2: count++; break
case 4: count--; break
}
};
this.nativeSend(body);
};
return count;
})();
console.log(activeXhr);