XMLHttpRequest - Parsing out attributes - JS - javascript

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));
}
}

Related

What is the proper way to call multiple XMLHttpRequests in the same/multiple script?

I think I ran into a problem of the same variable being used, I might have gotten lucky in some cases where they were separated by function scope. I recently replaced all of my jQuery code with plain JS and this broke a few things however the gained speed/lack of dependency(extra file to download) was good for me in this situation.
So I have the basic form of:
var http = new XMLHttpRequest(),
url = "php/my-script.php",
params = encodeURI('some-param='+value);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(data) {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var result = JSON.parse(http.responseText);
if (result['status'] === "success") {
someFunction(result['some_key']);
}
}
}
http.send(params);
When I ran into the problem of the same http variable being used, I started to replace new ones with http1, http2, etc... seems like a bad idea. Especially having to replace all the http-method(?) calls afterwards like http2.responseText, etc... Should I make this into a function... then pass in the values to post and return the data out?
I guess I don't understand what happens when you call:
var http = new XMLHttpRequest();
Is that a one time use case, where after it has been called you need a new one for another post?
I will try the single-global-function approach. Everywhere I needed to do an AJAX call whether get or post, I always just used $.post/$.get on the spot, not sure if that's bad.

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+"'";

Get xhr response and parse it

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');

XMLHttpRequest: POST request status

I have such part of code:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://someurl.com", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
doSomeTask();
}
}
}
xhr.send('login=mylogin&password=mypassword');
How can I know if my login&password are correct? In both cases xhr.status is 200.
Invalid Login/Password attempts are not HTTP failures. Only HTTP Failures return you 4xx or 5xx return codes. You might want to use the xhr.responseText or xhr.responseXML from the response to see what your backend is returning and base your decision according to that. Please refer to http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#dfn-responsetext for how the responses are obtained.
Also, there are tons of good Javascript framework that hide the complexity of making Ajax calls. JQuery makes the job of calling AJAX scripts extremely easy. You might want to investigate on that instead of writing raw XHR code.

Categories