I am having trouble access data within an ajax connection. Not sure what is wrong with my code. It seems as though it never reaches the 2nd function. Any ideas?
function fetchgps(callback)
{
var url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";
var myRequest = new XMLHttpRequest();
myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
myRequest.open("GET", url);
myRequest.setRequestHeader("Cache-Control", "no-cache");
myRequest.setRequestHeader("wx", "385");
myRequest.send(null);
return myRequest;
}
function xml_loaded(event, request, callback)
{
if (request.responseText){
var obj = {error:false, errorString:null}
var data = myRequest.responseText;
collected=data.split(","); //parses the data delimited by comma and put data into array
obj.latitude = collected[4];
obj.longitude = collected[5];
callback(obj);
}
else
{
callback ({error:true, errorString:"XML request failed. no responseXML"}); //Could be any number of things..
}
}
function dealwithgps(obj)
{
lat = obj.latitude;
lon = obj.longitude;
document.write(lon);
document.write(lat);
}
fetchgps(dealwithgps);
Thats request.onreadystatechange instead of request.onload
function fetchgps(callback)
{
var url =
"http://www.instamapper.com/api?action=getPositions&key=584014439054448247";
var myRequest = new XMLHttpRequest();
// myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
myRequest.onraedystatechange = function() { //onraedystatechange instead of onload!!
xml_loaded(myRequest, callback);
}
myRequest.open("GET", url);
myRequest.setRequestHeader("Cache-Control", "no-cache");
myRequest.setRequestHeader("wx", "385");
myRequest.send(null);
return myRequest;
}
function xml_loaded(request, callback) {
if(request.readyState === 4) {
//... only then do your processing
}
}
Related
I have RestAPI endpoint providing simple response with single flag "needUpdate" true/false.
I am trying to write Javascript polling function which calls this endpoint and in case that needUpdate=true, it reloads whole web page.
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
}
};
xhr.send();
if(needUpdate == true){
location.reload();
} else {
poll();
}
}, 3000);
}
var json = JSON.stringify(poll());
It calls API every 3 seconds as expected and also states proper value of needUpdate into console. But reload does not happen.
It seems that needUpdate value is actualy undefined on the place where I tried to set a condition.
Can you please help me?
move condition inside xhr.onload function
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
if(needUpdate == true){
location.reload();
} else {
poll();
}
}
};
xhr.send();
}, 3000);
}
var json = JSON.stringify(poll());
Is it possible for me to call a function then override the contents of the variable before actually running it?
So I have a function that basically pulls in my Git profile like this:
var GetGitInfo = function() {
var xhr = new XMLHttpRequest();
var gitURL = "https://api.github.com/users/myself/repos";
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
Then I call the function in another step by doing GetGitInfo(); which all works fine.
However, If I wanted to call the function and replace the gitURL variable how would I achieve that?
So something like
GetGitInfo(
gotURL= "https://api.github.com/users/new_user/repo";
);
You can't modify a local variable to a function from outside the function. They are private to the function's implementation.
But, since it's your own function, you can just create an argument that can be passed into the function. You can even make the argument optional so it will take your initial value as the default value if it is not passed.
var GetGitInfo = function(url) {
var xhr = new XMLHttpRequest();
var gitURL = url || "https://api.github.com/users/myself/repos";
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
Then, you can use the function the way you were using it or you can pass in an URL to use:
getGitInfo(); // uses your default URL
getGitInfo("http://someURL"); // uses the URL you pass in
FYI, this function looks like it will ultimately need to either return a promise or accept a callback so you can communicate the results back to the caller.
From the snippet above you need to set the url as a function parameter so when calling it uses the specified url.
var GetInfo = function(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
GetInfo("https://api.github.com/users/myself/repos");
You should do a toString() on the function:
GetGitInfo.toString()
Then you should do a text search and replace on the variable and it's data:
GetGitInfo.toString().substring(0,GetGitInfo.indexOf('somestring'))+'gitUrl="newURL"'+GetGitInfo.toString().substring(.......)
Then you should eval that string!
Or, you know, use function parameters. Either way. Whatever's easiest.
Pass a parameter to the function:
var GetGitInfo = function(gitURL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
GetGetInfo("https://api.github.com/users/myself/repos");
Just add a parameter to your function:
var GetGitInfo = function(gitURL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", gitURL);
xhr.send(null);
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
} else {
console.log('Error: ' + xhr.status);
}
}
};
}
and call it like this:
GetGitInfo("https://api.github.com/users/myself/repos");
Use the parameters
var getData = function(url){
// url can be used here
}
var data = getData("http://apiurl.xy")
I am trying to call an ajax request to my server for json data using a function. If I console out the resp variable inside the ajax function it will show the data successfully. If i try to set the ajax function to a variable, and then console that variable it returns undefined. Any ideas who to make the function request the data and then set ti to a variable to be consoled?
function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp;
}
}
xhr.send();
}
jsonString = jsonData(http://mywebsite.com/test.php?data=test);
console.log(jsonString);
This is actually pretty simple.. Change your call to by synchronous..
xhr.open("GET", URL, false);
That being said this will block the browser until the operation has been completed and if you can use a callback instead it would likely be preferred.
function jsonData(URL, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
cb(resp);
}
}
xhr.send();
}
jsonData("http://mywebsite.com/test.php?data=test"
, function(data) { console.log(data); });
I have four functions that handle a certain part of my app for getting a photo url.
In the function handleGetPhotoResponse the alert has my url in it, everything looks like it should.
The problem is in the function handleGetUsersFurKidsResponse. the variable "fkimg" is undefined. Can anyone tell me where I went wrong?
To use this part of the app I make a call to "getUsersFurKids".
function handleGetPhotoResponse(responseText, size) {
var photoDetails = JSON.parse(responseText);
var thePhoto = photoDetails[size];
alert(thePhoto);
return thePhoto;
}
function getPhoto(id, size) {
var url = "url-removed"+id;
var request = new XMLHttpRequest();
//Send the proper header information along with the request
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
return handleGetPhotoResponse(request.responseText, size);
}
};
request.send(null);
}
// function to handle the response of getting a users fur kids
function handleGetUsersFurKidsResponse(responseText) {
var ul = document.getElementById("furKidList");
var furKids = JSON.parse(responseText);
for(var i = 0; i<furKids.length; i++){
var li = document.createElement("li");
var fkimg = getPhoto(furKids[i].ui_id, 'small');
li.innerHTML = "<a href=\"\"><img src=\""+fkimg+"\"> "+furKids[i].p_name;
ul.appendChild(li);
}
}
// function to get a users fur kids
function getUsersFurKids(id) {
// api url for getting fur kids
var url = "url-removed"+id;
var request = new XMLHttpRequest();
//Send the proper header information along with the request
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
handleGetUsersFurKidsResponse(request.responseText);
}
};
request.send(null);
}
// receive a callback---v
function getPhoto(furKid, size, callback) {
// ^---and the current furKid
// use the ui_id------------v
var url = "url-removed" + furKid.ui_id;
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
// Invoke the callback, and pass it the result of handleGetPhotoResponse
callback(handleGetPhotoResponse(request.responseText, size), furKid.p_name);
// use the p_name-----------------------------------------^
}
};
request.send(null);
}
function handleGetUsersFurKidsResponse(responseText) {
var ul = document.getElementById("furKidList");
var furKids = JSON.parse(responseText);
for(var i = 0; i<furKids.length; i++){
// pass a callback-----------------v
getPhoto(furKids[i], 'small', function(fkimg, p_name) {
var li = document.createElement("li");
li.innerHTML = "<a href=\"\"><img src=\""+fkimg+"\"> "+ p_name;
ul.appendChild(li);
});
}
}
You don't seem to understand that getPhotos is an asynchronous function. The onload handler inside it is called sometime LATER long after the getPhoto function itself returns and is finished. As such, you CANNOT return a value from getPhoto that was retrieved in onload.
Instead, you have to put all code that needs to use the onload response from getPhoto inside of the onload handler itself (or called from inside the onload handler) because ONLY when the onload handler is called is that data known.
This is how asynchronous programming works in javsacript.
Add a callback to getPhoto and call that callback from inside the onload handler, passing it the img that you got from the async call. Then, and only then, can you use that img data.
I'm created this class to fetch a file from web to check for new version using Ajax.
This code run on a Windows gadget, on IE8. But I'm having trouble because of the cache.
Is there a way to fix this Ajax class to disable cache?
PS: I don't use any library or frameworks.
var ClassAjax = function() {
this.data = null;
var that = this;
this.get = function(url, send) {
var ajax = new function ObjAjax() {
try{ return new XMLHttpRequest(); }
catch(e){try{ return new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e){ return new ActiveXObject("Microsoft.XMLHTTP"); }}
return null;
}
ajax.onreadystatechange = function() {
if(ajax.readyState == 1) { that.onLoading(); }
if(ajax.readyState == 4) { that.data=ajax.responseText; that.onCompleted(that.data); }
}
ajax.open("GET", url, true);
ajax.send(send);
};
this.onLoading = function() {
//function called when connection was opened
};
this.onCompleted = function(data) {
//function called when download was completed
};
}
var request = new ClassAjax();
request.onCompleted = function(data) { alert(data); }
request.get('http://exemple.com/lastversion.html', null);
You can pass the current timestamp as a variable in the url, like this :
var timestamp = new Date().getTime();
ajax.open("GET", url+'?ts='+timestamp, true);
Also, you can force the page to be reloaded on server-side, using the proper headers