My ajax call looks like this:
request = new XMLHttpRequest();
request.open("GET","/showChamps?textInput=" + searchChamp.value,true);
request.send(null);
request.onreadystatechange = function () {
if (request.status == 200 && request.readyState == 4) {
//how do i get my array
}
};
}
I have sent an array from my node.js server but I don't know how to get that array because request.responseText does not give me back an array. Also it would be appreciated if the answer is in javascript.
Thanks in Advance!
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
var responseHTML = xhr.responseText, // HTML
responseXML = xhr.responseXML, // XML
responseObject = JSON.parse(xhr.responseText); // JSON
}
};
Related
hi after searching in the net about how to use the long polling in JavaScript I ended up with three ways, they are mentioned here briefly,but they are implemented using JQuery. I am confused which one to use in case that the AJAX request that I send to the server is asynchronous GET request ,and I don't know how many time it could take.
here is an example AJAX request:
function asynchGETRequest(method,url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("ok");
}
};
xhttp.open(method, url, true);
xhttp.send();
return (xhttp.responseText);
}
var clientFunctions={
getAnswers : function(callback){
var res=asynchGETRequest("GET", "http://localhost:9000/answers");
callback(JSON.stringify(res));
}
}
clientFunctions.getAnswers (function(){
//do some code here after the ajax request is ended
});
can some one guide me please?
I think I found the solution here
function loadFile(sUrl, timeout, callback){
var args = arguments.slice(3);
var xhr = new XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.apply(xhr, args);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = timeout;
xhr.send(null);
}
I have a textarea where users can enter multiple URLs which in return will be used for an API request.
The issue I run into is that only the last URLs API request gets captured (sometimes multiple times).
$('.start').on('click',function()
{
var url_list = $("#url-list").val();
var urls = url_list.split("\n");
for (var i = 0, len = urls.length; i < len; i++) {
console.log("i is "+i)
var xhr = new XMLHttpRequest();
xhr.open('GET', urls[i], true);
xhr.send();
xhr.onreadystatechange = processRequest;
// send API request
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
}
}
});
I don't see exactly where I am doing something wrong, I might be blind to it or just don't know any better. Any help would be appreciated. PS. fairly new to making API requests.
Welcome to closures.
The problems here are:
The loop could be finished before the first request starts, so it takes the last url in the array
In the callback you are referencing the same xhr object
You can try one of the different solutions here.
Replacing xhr with this in the callback is the fastest fix:
function processRequest() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
}
}
See this fiddle for a running example.
You could update your code like this
var requestIndex = 0;
var urls = [];
$('.start').on('click',function()
{
// Reset request index
requestIndex = 0;
var url_list = $("#url-list").val();
urls = url_list.split("\n");
// Send Http request
sendRequest(urls, requestIndex);
});
// Send Http request
function sendRequest(urls, index) {
// Send API request
var xhr = new XMLHttpRequest();
xhr.open('GET', urls[index], true);
xhr.onreadystatechange = processRequest;
xhr.send();
}
// Process API request
function processRequest(e) {
if (e.target.readyState == 4 && e.target.status == 200) {
var response = JSON.parse(e.target.responseText);
console.log(response);
}
requestIndex++;
if (requestIndex < urls.length) {
sendRequest(urls, requestIndex);
}
}
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've been working on a single page site in which data from a single json file is rendered variously in different sections - nothing displayed on load, but only upon click event. I learned a little about callbacks getting that wired up, but as I almost completed it I realized how flawed the concept was, so now I'm back to the drawing board.
My idea now is to make the ajax call onload, set the json result as a variable available to several functions. I thought it would go something like this:
window.onload = function() {
var myJsonData = function() {
var request = new XMLHttpRequest();
request.open("GET", "/json/someJsonData.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
var myJsonArray = myJsonString["Projects"];
return myJsonArray;
}
}
} // onreadystatechange
} // var myJsonData
myJsonData(); // *
console.log("myJsonArray: " + myJsonArray); // undefined
Or:
window.onload = function() {
myJsonData();
}
function myJsonData() {
var request = new XMLHttpRequest();
request.open("GET", "/json/someJsonData.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
var myJsonArray = myJsonString["Projects"];
alert("you are here (myJsonArray defined)");
alert("myJsonArray: " + myJsonArray);
console.log("myJsonArray: " + myJsonArray);
return myJsonArray;
}
}
} // onreadystatechange
} // var myJsonData
console.log("myJsonArray: " + myJsonArray); // undefined
Or:
window.onload = myJsonData;
// etc.
Of course myJsonArray is undefined either way. I'm obviously missing something fundamental about how to do this (or is this even a bad idea altogether?). Is there some way to pass a result as a callback when invoking an ajax request on load?
Can someone please enlighten me as to how to proceed from here, a skeletal example perhaps ? (p.s. still focusing on native js, not jQuery)
Many thanks in advance,
svs
There are some things wrong in the code. First the myJsonArray is local to the function myJsonData(). You have to define it globally. Second, the ajax request is async. You have to wait for the result before working with it. Here is a working example based on your code:
var myJsonArray; //Globally defined
window.onload = function() {
var outputData = function() {
console.log(myJsonArray);
}
var myJsonData = function() {
var request = new XMLHttpRequest();
request.open("GET", "someJsonData.json", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
myJsonArray = JSON.parse(request.responseText);
outputData(); //Ouput when result is received
}
}
} // onreadystatechange
} // var myJsonData
myJsonData(); // *
}
Using Javascript promises could solve your problem here. Promises are native to ES6, although obviously the browser support isn't quite fully there yet. Regardless, here is how you could implement your code with promises:
window.onload = function () {
myJsonData().then(function (result) {
console.log("myJsonArray: " + result);
alert(result.one);
// do something else here
});
}
function myJsonData() {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open("GET", "http://echo.jsontest.com/key/value/one/two", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
//var myJsonArray = myJsonString["Projects"];
resolve(myJsonString);
}
}
} // onreadystatechange
});
} // var myJsonData
Here is a jsfiddle
From my experience and understanding.
When you are dealing with sync function and async function, always it is important to know which functions require data from the async callback function.
If the functions fully depend on the data received, it will a good coding practice to call these function in the loop
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
// call the function which depend on the data received here.
}
}
I wouldn't recommend setting the async as false as it would just result in page freeze sometimes.
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); });