I have recently learned to use APIS in code, but for my javascript version I've had to learn different ways of doing it, when using what should be the simplest method nothing gets outputted to my chrome console.
const request = new XMLHttpRequest();
request.open('GET','apistuff, true);
request.onload = function() {
let data = JSON.parse(this.response);
console.log(data);
};
HTML file is just empty and calls the javascript file
Just replace current code with below code and let me know the status
const request = new XMLHttpRequest();
request.open('GET', apistuff, true);
request.send();
// we need to call this send method to open breach between server and client
request.onload = function() {
let data = JSON.parse(request.response);
// if response is in text simply use **request.responseText**
console.log(data);
};
Related
i am trying to learn Ajax now i don't know how to set XMLHttpRequest Asynchronous. i've tryed some other post about ajax but can't make sense of it. Sorry if this already asked.
In the following code i try to console.log the XMLHttpRequest object.
i've linked it to a local text file in the same folder.
the problem is that when is set request.open parameter to true it does't work. Its only works when its set to false but i read that this is not asynchronous.
I am using XAMPP for a server. Also i've tryed it on a differnt server form school.
If there are anny questions please ask me.
thanks
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Mircosoft.XMLHTTP");
}
//this open function
request.open('GET', 'text.txt', true);
request.send();
if(request.status===200){
console.log(request);
document.writeln(request.responseText);
}
The entire point of it being asynchronous is that it won't lock up the JavaScript engine until the response has arrived. So with your current code, you are trying to read the response before it exists.
You need to use an event handler to process the data after it has arrived.
function processData() {
document.writeln(this.responseText);
}
var request = new XMLHttpRequest();
request.open('GET', 'text.txt');
request.addEventListener("load", processData);
request.send();
You've to wait the response with request.onreadystatechange function
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200)
{
document.writeln(request.responseText);
}
}
//this open function
request.open('GET', 'text.txt', true);
request.send();
i'm trying to access a local JSON File with JS, turn it into an JS Object by parsing it and logging it to the console. I'm using Live Server in VS Code to set up the Server, therefore the localhost URL.
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
var jsonObj = request.response;
request.onload = function () {
JSON.parse(jsonObj);
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
//console.log("jsonObj[Datum]= " + jsonObj[Datum]);
//console.log("jsonObj.Datum= " + jsonObj.Datum);
}
Output: jsonObj= null
The JSON File:
{
"Datum": ["03.05.2017","05.06.2017"],
"Volume": [1338,1445]
}
Here's what I imagine happens:
I'm getting the Answer from localhost and parsing it via JSON.parse into an JS Object. As soon as the request finished im calling my logData function and passing the parsed Data to log it.
As #connexo pointed out I didn't understand the asynchronous nature of the call. And frankly i still don't but i guess a good starting points will be:
How do I return the response from an asynchronous call?
MDN Synchronous and Asynchronous Requests
As #Mani Kumar Reddy Kancharla pointed out my response is already a JS Object since i declared request.responseType = 'json';
This is how it looks right now:
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function () {
console.log(request.response);
var jsonObj = request.response;
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
console.log("jsonObj[Datum]= " + jsonObj.Datum);
Ouput: {…}
Datum: Array [ "03.05.2017", "05.06.2017" ]
Volume: Array [ 1338, 1445 ]
jsonObj= [object Object]
jsonObj[Datum]= 03.05.2017,05.06.2017
As you can see i can also access the .Datum Property. I Consider it solved. Thank you!
edit: Added the link provided by connexo.
I used the browser XMLHttpRequest object for Ajax about 12 years ago.
https://api.jquery.com/jquery.getjson/
You have two issues in your code:
You're using JSON.parse() too many times on same date which is already converted from JSON string to a JavaScript object and tries to parse a Javascript object raising a Syntax error. You've already mention request.responseType = 'json' i.e. responseType specifies you're receiving a JSON string as response so JavaScript Engine will already parse it and provide you a JavaScript object as request.response and you need not parse it. So you could use JSON.parse(request.responseText) if you want to parse it yourselves or directly use request.response as a JavaScript object.
You're trying to store request.response into a variable outside the load function which will just provide the value of request.response at that time which could be null if the response is not received yet. You need to get the response in the onload fucntion implementation as it is executed once you receive the response.
So what you're looking for overall is this ->
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
var jsonObj;
function logData(jsonObj){
console.log("jsonObj= " + JSON.stringify(jsonObj));
console.log("jsonObj[Datum]= " + JSON.stringify(jsonObj["Datum"]));
console.log("jsonObj.Datum= " + JSON.stringify(jsonObj.Datum));
// or simply
console.log(jsonObj);
console.log(jsonObj['Datum']);
console.log(jsonObj.Datum);
}
request.onload = function () {
jsonObj = request.response;
logData(jsonObj);
};
request.responseType = 'json';
// finally send the request
request.open('GET', requestURL);
request.send();
Here JSON.stringify() converts a JavaScript Object back to a JSON string.
Refer to this link to get more information on how to use XMLHttpRequest
EDIT: Referring to another answer posted, people simply use libraries like jQuery AJAX to make asynchronous requests to get data from the web, especially in XML or JSON format.
I am using an external payment site to redirect to my own website. I need some of the form data in the headers and I cannot figure out how to grab the data. Here is a screenshot:
Inside the headers tab, I want to get the information from the Form Data tab.
The code below is what I was able to find regarding getting headers, but the problem is it only grabs the code from the ResponseHeaders tab. And req does not have any function to get the form data.
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
I want to see if there is a function where I can do something like
var formData = req.getFormData().toLowerCase();
There is no way, in browser-side JavaScript, to get information about the request that was used to get the current page from the server.
If you want access to it, you'll need to use server side code to dynamically generate the page and include it in the DOM (perhaps as a JavaScript object in a <script> element, or as a data-* attribute, or in <meta> elements) and then use JS to extract it from the DOM.
The mozilla site provides an example (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader)
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(client.getResponseHeader("Content-Type"));
}
}
But fetch is nicer (see https://developer.mozilla.org/en-US/docs/Web/API/Response/headers):
fetch(myRequest).then(function(response) {
console.log(response.headers); // returns a Headers{} object
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});
I have this snippet below to fetch how score count on shared links on Reddit. Using Google Chrome I get a JSON response I can work with, but in Safari the same code sends me directly to "onerror" instead.
Help please :)
UPDATE 1
For some reason it doesn't work for me but for everyone else. I have all plugins disabled but can only get it to work in incognito mode.
UPDATE 2
It seems it affect some people using Safari, but not all. Safe to say, the fault must be in the browser and not in my code :)
var myurl = 'http://www.google.com';
var jsonURL = 'http://www.reddit.com/api/info.json?url=' + myurl;
var request = new XMLHttpRequest();
request.open('GET', jsonURL, true);
request.onload = function () {
console.log('ON LOAD ------------------------------');
var response = JSON.parse(request.response);
console.log(response);
};
request.onerror = function () {
console.log('ON ERROR ------------------------------');
console.log(request);
};
request.send();
I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});