Storing XHR request into javascript variable - javascript

I am having trouble storing the response of my XHR request.
Here is the javascript so far:
var req = new XMLHttpRequest;
req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
req.responseType = 'json';
req.send();
Over at chrome dev tools, i can see that response is the items i want so request should be fine. It is status of 200 and state 4.
The problem becomes when i try to write
var myJSON = req.response;
When i log this to console it responds with "null".
But if i reassign the value through dev tools, to exactly the same value, i get my JSON object.. Can someone please explain to me why and how i can fix this?

try with ready state
var req = new XMLHttpRequest;
req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
req.responseType = 'json';
req.send();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.response);
var myJSON = this.response;
}
};

Related

XMLHTTPRequest POST getting stuck

I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?
You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.

ajax fail to POST on API

i tried everything, and i still cant figure out whats the problem, i'm trying to 'POST' something on teachers server that we had for homework, and i have no idea what i'm doing wrong ,i'm stuck for like 2 hours already.
here is my code.
const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
console.log(xhr.response);
}
}
xhr.open('POST',url);
xhr.send(attendee);
Please see this snippet, you are getting The 401 Unauthorized error, you have to attach authorization token variable to the request.
xhr.setRequestHeader('Authorization', '~Token~');
There will be an other api that will get authorization token.
const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
console.log(xhr.response);
}
else{
console.log(xhr.status);
}
}
xhr.open('POST',url);
xhr.send(attendee);

Asynchronous request in react-native

I use this piece of code to asynchronously make a request with React-Native, but it seems like it doesn't get it. The request has been tested separately and the data should be valid.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
req.open('GET', testedValidUrl, true);
req.send();
req.onreadystatechange = processRequest;
var name ="";
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
// setTimeout(()=>{},1000);
}
I thought that maybe it was because of concurrence and that the large array in the real application takes less time to construct than to get the data from the server. Adding setTimeout() did not fix it.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
req.onreadystatechange = processRequest;
req.open('GET', testedValidUrl, true);
req.send();
var name ="";
If you set the event handler, (onreadystatechange) after you send/open the request, the readyState has already changed and thus it won't be called.

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

Categories