I'm very new to coding, I'm hoping someone can help me. I have this little bit of code, I am trying to learn this process:
Call Made to URL via GET request (json)
Parse the response from the GET request
Save the response into a variable that I will use later
Any and all help is appreciated!
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const awsURL = 'https://cors.io/?http://status.aws.amazon.com/data.json';
function Get(awsURL){
var request = new XMLHttpRequest();
request.open("GET", awsURL, false);
request.send(null);
return request.responseText;
}
var AWSJson = JSON.parse(Get(awsURL));
console.log("Archived Outages: "+AWSJson.service_name);
Return value in given address is not in correct json format. Enter the url in your browser and check the output !
Related
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'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
I wanted to know if there was a way I can receive information from API through JavaScript. I'm currently trying to use the information from API from www.openweathermap.org but I'm not sure how I can do it with JS. I currently tried
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?
lat=38.892634199999996&lon=-77.0689154", false);
xhr.send();
console.log(xhr);
which responds and sends me information in JS Object format:
{ response: {"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,"main":"Clear",
"description":"sky is clear","icon":"01d"}],"base":"cmc stations","main":{
"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,"temp_max":304.15},
"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},"dt":1436565479,
"sys":{"type":1,"id":1325,"message":0.008,"country":"US","sunrise":1436521925,
"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200}\n',
responseText: '{"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,
"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"cmc stations",
"main":{"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,
"temp_max":304.15},"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},
"dt":1436565479,"sys":{"type":1,"id":1325,"message":0.008,"country":"US",
"sunrise":1436521925,"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200} }
I tried console.log(xhr.response.coord) and console.log(xhr.responseText.coord) as an example and both comes out undefined. Do I need to do something else to print out the information?
I know you can use $.get(URL, function()) to receive the information via JQUERY but is there a way I can do it just JS?
You should parse the string as a JSON object. Like this:
var data = JSON.parse(xhr.response);
console.log(data.coord);
You are missing the response handler
var xhr = new XMLHttpRequest();
// when the async call finishes, we need to check what happened
xhr.onreadystatechange=function(){
// if it finished without errors
if (xhr.readyState==4 && xhr.status==200){
// we get the data
var data = JSON.parse(xhr.responseText);
// this should be your json
//console.log(data.response.coord);
document.getElementById('response').innerHTML = xhr.responseText;
}
};
// NOTE! for demo purposes I'm using another api query that does not require an api key, change this to your api url
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk", false);
xhr.send();
<div id="response"></div>
Your response is in JSON so you need to parse it first.
Use JSON.parse(xhr.response) to parse the response.
Like this:
JSON.parse(xhr.response)["coord"]["lat"]
JSON.parse(xhr.response)["coord"]["lon"]
I'm trying to make a little script to rehost pictures on the web on imgur.
This is called Image Sideloading and you only need to point the browser to http://api.imgur.com/2/upload?url= + Picture's Url
It doesn't return any XML or JSON response so I can't parse it to get the img URL.
But I think I found a way to do this but can't get it to work properly. Here's the code I'm using.
$(document).ready(function() {
$("#button").click(function() {
str = $("input").val().toString();
link = "http://api.imgur.com/2/upload?url=" + str;
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.send();
var headers = xhr.getAllResponseHeaders().toLowerCase;
alert(headers);
});
});
And looking at Google Chrome's console these are the results generated after the script runs.
I am not allowed to post images yet so here's a link to the results: http://i.imgur.com/xCyIP.png
I need to somehow access that 4th response header because even though this method doesn't return any parsable XML or JSON response that link is the uploaded img's URL which is all I need.
So is there a way to access that info? Why is it cancelled?
Thanks everyone!
Well, the API must return something, else it is useless.
Actually, http://api.imgur.com/examples advises you to do something like:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
var url = JSON.parse(xhr.responseText).upload.links.imgur_page;
alert(url);
}
xhr.send();
Edit. OK, I got it. Normally, the above code should work, but I think imgur is facing a problem. I will report the bug.
While the bug is still there, here is a dirty solution to serve your needs:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
html = xhr.responseText;
alert(html.substr(html.indexOf('http://i.imgur.com/') + 19, 5));
}
xhr.send();
You code wasn't working because you weren't waiting for the answer. You have to catch it through a callback function.
Edit. The above code only works locally. As you're using jQuery, let me introduce the shortcut $.post:
$(document).ready(function() {
$("#button").click(function() {
$.post('http://api.imgur.com/2/upload.json', {
key: 'ec575de603b936e54c2b4a9f232d537e',
image: $("input").val().toString()
}, function(data) {
alert(data.upload.image.hash);
});
});
});
http://jsfiddle.net/Le_Sphinx/rEfdS/
I need to pass huge amount of data to server without page loading. I have this code:
var GlType = "<%=GlType %>";
var pageUrl = "SelectAccount.aspx?callback=true&AccountList=" +accountList +"&AnalysisDate="+analysisDate+"&GlType="+GlType;
if (window.XMLHttpRequest)
{
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("POST", pageUrl, true);
xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlRequest.send(null);
I am have passed using query string its exceeded the maximum Length of query string. Help me on this..
Since you're already using the POST method, you can pass data in the body.
xmlRequest.send("Field1=abc&Field2=def");
You can retrieve the data on the server, e.g. in ASP.NET:
if (Page.Request.Form["Field1"] == "abc") ...
For GET method you can only use the query string for transferring data.
You're sending the request via post, but putting everything in the query string!
Instead, you should send the data as the body of the request (passed to the send method).