Get xhr response and parse it - javascript

Hi I make an xmlHttpRequest like this:
var xhr = new XMLHttpRequest();
var params = 'gbook_text=' + encodeURIComponent('sdfsdf');
xhr.open("POST", '/gbook/save/7697256.html', true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.send(params);
And I need to parse some data from response which is just a webpage
I need to parse It via dom methods like getElementById().
I know that I can write something like:
xhr.responseXML.getElementById('author')
But it works only if server sets a header
Content-Type: text/xml
Otherwise responseXML is null
So what are my options?
P.S: only js without any libraries.
P.P.S: browser requirements: chrome, ff, ie8+
Edited: okay options, which one is better:
1)parse xhr.responsetext as a string
2)redirect to response page and parse it.How to do it, btw?

If i understand your question, you can only get your response back in text, yet you want to search for it as an HTML document, you can try creating a div and putting the html response as the innerHTML of the div.
var res = document.createElement( 'div' );
res.innerHTML = xhr.responseText;
res.querySelector("#ElementID")

Have you tried setting the responseType and/or using the overrideMimeType method?
xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');

Related

XMLHttpRequest - Parsing out attributes - JS

First off, this is a complete newbie question. I don't really have much idea of what I'm doing.
I have an API that returns the top 10 fund raisers from JustGiving. I can get the XML info to display, however it just dumps everything out all together. This is what JS I have so far:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.justgiving.com/{appid}/v1/event/{eventID}/leaderboard?currency=gbp/", true);
xhr.responseJSON;
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
document.write(xhr.responseText);
}
}
I have been look for hours at different ways to get this information output into something I can manipulate on a web page. Something that can be wrapped in a div.
Pretty sure its this I need to modify...
document.write(xhr.responseText);
Please help or point me in the right direction. Or if I've gone completely in the wrong direction let me know. There is probably already a solution out there, but as my knowledge is very limited I'm probably wording all my searches wrong.
The documentation for the API is https://api.justgiving.com/docs/resources/v1/Leaderboard/GetEventLeaderboard
Many thanks in advance.
Since you're in JS, I'd avoid working with XML if at all possible.
The JustGiving API should also be able to provide a JSON response, if you include the appropriate header on your request.
Something like:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.justgiving.com/{appid}/v1/event/{eventID}/leaderboard?currency=gbp/", true);
// Add accept header to indicate you want JSON
xhr.setRequestHeader("Accept", "application/json");
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
// Parse the JSON in the response
document.write(JSON.parse(xhr.responseText));
}
}

chrome extension http request to website

I wanted to make a chrome extension that gets the html code from this website: https://free-proxy-list.net/
without actually going to that webpage.
I tried using the steps here:
https://developer.chrome.com/extensions/xhr
but the request kept showing as undefined when I tried to print it out.
The script I was using was:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', "url", true);
xhr.send(null);
document.write(xhr.send());
Note: not putting url in code since SO won't let me post a question with more than 2 links.
How would I get the code from this website in a string variable that I can parse?

XMLHttpRequest POST parameter encoding

I want to submit a POST request while passing a url among other parameters.
I have the following script but it is not working.
var params = "param1="+param1_value+"&url="+url_value;
var xhr = new XMLHttpRequest();
xhr.open("POST", action_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log("Done");
}
}
xhr.send(params);
Assuming that the url_value is something like this:
https://www.domain.com/blah?param=&email=domain%40email%2Ecom&blah=1234
what would be wrong with this script?
Take a look at this question/answer - Should I URL-encode POST data?
Your sample value for url_value is using the HTML Entity Code. Because of the & symbol in the value, it is being sent as multiple values. You probably need to URL encode it so it looks like this
https%3A%2F%2Fwww.domain.com%2Fblah%3Fparam%3D%26email%3Ddomain%40email.com%26blah%3D1234
You may have a problem when trying to access another domain/website. The receiving side must have the Access-Control-Allow-Origin header in its return message.
You can probably find your solution in this answer.
You are missing quotation to the url string value,alert the parameter string as below
var params = "param1='"+param1_value+"'&url='"+url_value+"'";

obtain information from API javascript

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"]

XMLHttpRequest HTTP Headers

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/

Categories