I've been searching on the web for some time and couldn't find an example of how to use the GitHub API from plain client-side javascript (no node-js, jquery etc). I wanted something like authenticate then push a blob, put as simply as possible so I can understand it. Shouldn't be too complicated, I bet you can do that in a dozen lines of code but I don't know a lot about ajax, json and jsonp.
Can you provide an example to get me started?
Thanks!
edit: found this: http://blog.vjeux.com/category/javascript, but I'm still confused as to what are exactly the steps of the process.
If you're looking to use with vanilla JavaScript (i.e. no framework), you need to play around with the XMLHttpRequest object. The XMLHttpRequest provides the core for AJAX implementations.
Despite the XMLHttp prefix, you're not limited to XML or HTTP. You can retrieve any data type (such as JSON) and use other protocols such as FTP.
Say we'd like to GET your user information from GitHub. From a browser, we can easily make the request by visiting https://api.github.com/users/funchal.
Sending an HTTP request in JavaScript is just as simple with XMLHttpRequest:
// Create a new request object
var request = new XMLHttpRequest();
// Initialize a request
request.open('get', 'https://api.github.com/users/funchal')
// Send it
request.send()
If you give this a go from a JavaScript console, you might feel a bit disappointed: nothing will happen immediately. You'll have to wait for the server to respond to your request. From the time you create the instantiate the request object till when the server responds, the object will undergo a series of state changes denoted by the value of the readyState property:
0 UNSENT: open() uncalled
1 OPENED: send() uncalled
2 HEADERS_RECIEVED: headers and status are available after a send()
3 LOADING: the responseText is still downloading
4 DONE: Wahoo!
Once all is finished, you can check the response attribute for the data:
request.readyState // => 4 (We've waited enough)
request.response // => "{whatever}"
When using XMLHttpRequest#open(), you have a few options to consider. Here's the method signature:
void open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
);
The third parameter, which defaults to true, dictates whether the response should be made asynchronously. If you set this to false, you'll have to wait until the response is complete for #send() to return, and you'll pay the price of blocking your whole program. As such, we code in an asynchronous fashion so that our program remains responsive even while we wait. This asynchronicity is achieved by using and event listeners (a.k.a. event handlers) and callback functions.
Say we want to simply dump the response to the console once it arrives. We first need to create a callback function that we'd like to execute onload:
function dumpResponse() {
// `this` will refer to the `XMLHTTPRequest` object that executes this function
console.log(this.responseText);
}
Then we set this callback as the listener/handler for the onload event defined by the XMLHttpRequest interface:
var request = new XMLHttpRequest();
// Set the event handler
request.onload = dumpResponse;
// Initialize the request
request.open('get', 'https://api.github.com/users/funchal', true)
// Fire away!
request.send()
Now since you'll be receiving the data as a string, you'll need to parse the string with JSON.parse() to do anything meaningful. Say I want to debug the number of public repositories you have along with your name. I can use this function to parse the string into JSON, and then I can pull the attributes I want:
function printRepoCount() {
var responseObj = JSON.parse(this.responseText);
console.log(responseObj.name + " has " + responseObj.public_repos + " public repositories!");
}
var request = new XMLHttpRequest();
request.onload = printRepoCount;
request.open('get', 'https://api.github.com/users/funchal', true)
request.send()
// => Giovanni Funchal has 8 public repositories!
See the W3C spec and the Mozilla Developer Network for more info on XMLHttpRequest.
Related
Is there an event that'll run whether on success or error with Node.js's XMLHttpRequest module? According to the docs, the onloadend event should trigger both on error and success, but it only runs on success. For example:
var XMLHttpRequest = require( 'xmlhttprequest' ).XMLHttpRequest;
var url = 'https://www.example-bad-url.com/json.php';
var xhr = new XMLHttpRequest();
xhr.open( 'GET', url );
xhr.send();
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed, whether successfully or unsuccessfully.' );
}
In the above script, onloadend doesn't run, why? The URL doesn't exist, so it should trigger onloadend as an error and log "The request has completed..." but the callback function never runs, why?
The xmlhttprequest library for node.js does not fully implement the spec correctly.
If we dig into the code on github, we see the following line of code:
if (self.readyState === self.DONE && !errorFlag) {
self.dispatchEvent("load");
// #TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
self.dispatchEvent("loadend");
}
So the load and the loadend event handlers are only triggered when there is NOT an error, consistent with our observations where
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed.' );
};
will only log when the event succeeded.
My advice would be to trigger the event manually in the .onerror() handler, which does work. Keep in mind that this is a 3rd party node.js module, not a native one.
Personally I just wrote a small wrapper around xmlhttprequest that mimics the .fetch() interface. The node.js version uses the native node.js http library and the client side version uses xmlhttprequest.
That way I can use the same .fetch() API for both front end and back end code, and just let the system decide if it'll use native fetch, xmlhttp powered fetch, or http powered fetch.
First of all I have to say that I have NO EXPERIENCE in Ajax and I just need this one explanation in order for me to create a simple chrome extension.
There is not much I could find on internet even tho I believe this is very simple.
I need a part of code where I would "call" url from website and I need to adjust certain arguments in that url.
Request URL:http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE
Request Method:POST
Request Payload :
{amount: 1, user_id: 12345678}
amount: 1
user_id: 12345678
(this is something I get from Network panel- with url and token changed to real things - while calling url automatically from website, but I need to be able to call it manually too.)
So I have an idea of mixing AJAX(which I don't know) and JS in order for me to call this url.
I would use variables for both TOKEN_VALUE and amount&user_id, but I don't know how to even call that url and how to set "request payload" in order for site to do the thing I want it to do.
I would really appreciate if someone would be kind enough to help :)
Work I have done, but doesn't work:
var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");
I basically tried to remake an example I found online, but it didn't work out, therefore I need someone to actually explain to me how this works and how can I adjust arguments that I need.
function callAjax() {
// the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
// #data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
var request = new XMLHttpRequest(),
url = 'place_here_the_url_only',
data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
token = document.querySelector('meta[name="csrf-token"]').content;
// when the server is done and it came back with the data you can handle it here
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do whatever you want!
console.log("The request and response was successful!");
}
};
// method post, your giving it the URL, true means asynchronous
request.open('POST', url, true);
// set the headers so that the server knows who is he talking to, I'm using laravel 5.5
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Token needed
request.setRequestHeader('X-CSRF-TOKEN', token);
// then you send the data and wait for the server to return the response
request.send(data);
}
Ajax: Asynchronous JavaScript And XML
It is a mean of communication between the browser and the server hosting the website, it cannot call any other server.
Asynchronous means the website continues to function normally, until the request is returned from the server and the:
if (this.readyState == 4 && this.status == 200) { }
gets triggered
I'm trying to improve the UX on a few pages by adding some ajax. I have an ajax request:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/search/', true);
xhr.onload = function(data){
document.getElementById("search-results-container").innerHTML = data;
}
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(form_data);
This isn't giving me the rendered template from my django development server. Instead I get [object ProgressEvent] in my #search-results-container div. The django view renders correctly if I submit the request synchronously.
I'm probably completely misunderstanding the spec, but aren't I supposed to get the template data + http headers straight back from the server? What have I done wrong here?
The event handlers for XHR events are passed event objects. Newer browsers support the ProgressEvent API. Those won't give you the data from the request, however; for that you'll need to retain access to the XHR object itself. The .responseText and (if appropriate) the .responseXML properties will contain your response content once the HTTP request has actually completed (which, in your "load" handler, it will have).
I am trying to make api call to get spotify albums in native javascript without using any js frameworks. I am running into issues where I am unable to send Oauth token using native js. For spotify I have client id and client scret. I can either use that or the Oa
(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.spotify.com/v1/albums", false);
xhr.send();
document.getElementById("results").innerHTML = xhr.responseText;
})();
function request(callback) {
var xobj = new XMLHttpRequest();
// true parameter denotes asynchronous
xobj.open('GET', YOUR_URL_HERE, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// This marks that the response has been successfully retrieved from the server
// Utilize callback
callback(xobj.responseText);
}
};
xobj.send(null);
}
I would definitely recommend taking a look at the link Frobber provided. It's always better to understand why something does/doesn't work rather than just getting it to work. Here is a mock request to get you started. Hope this helps!
I think you need to read a basic tutorial on how to use XMLHttpRequest, which you can find here
One immediate problem with your code is that it's not using any callback to read the result that comes back from the server. This is all happening asynchronously, so what's occurring in your case is that you're send()ing the request, and then immediately setting innerHTML to a value that probably isn't even available from the server yet.
Check the tutorial for how to get that information back from the server when it's ready.
Note the use of the myFunction callback, and note the use of onreadystatechange. What's happening here is that send() is sending something to the server, in a separate execution thread. You need to register a callback function that will perform the data fetching and DOM update when the server reports back that the data is available, not immediately.
Using getAllResponseHeaders in the xhr object, is possible to get all the response headers after an ajax call.
But I can't found a way to get the Request headers string, is that possible ?
If this is for debugging purposes then you can just use Firebug or Chrome Developer Tools (and whatever the feature is called in IE) to examine the network traffic from your browser to the server.
An alternative would be to use something like this script:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
However I think only the headers already defined in headers is available (not sure what happens if the headers are altered (for instance in beforeSend).
You could read a bit more about jQuery ajax at: http://api.jquery.com/jQuery.ajax/
EDIT: If you want to just catch the headers on all calls to setRequestHeader on the XMLHttpRequest then you can just wrapp that method. It's a bit of a hack and of course you would need to ensure that the functions wrapping code below is run before any of the requests take place.
// Reasign the existing setRequestHeader function to
// something else on the XMLHtttpRequest class
XMLHttpRequest.prototype.wrappedSetRequestHeader =
XMLHttpRequest.prototype.setRequestHeader;
// Override the existing setRequestHeader function so that it stores the headers
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
// Call the wrappedSetRequestHeader function first
// so we get exceptions if we are in an erronous state etc.
this.wrappedSetRequestHeader(header, value);
// Create a headers map if it does not exist
if(!this.headers) {
this.headers = {};
}
// Create a list for the header that if it does not exist
if(!this.headers[header]) {
this.headers[header] = [];
}
// Add the value to the header
this.headers[header].push(value);
}
Now, once the headers have been set on an XMLHttpRequest instance we can get them out by examining xhr.headers e.g.
var xhr = new XMLHttpRequest();
xhr.open('get', 'demo.cgi');
xhr.setRequestHeader('foo','bar');
alert(xhr.headers['foo'][0]); // gives an alert with 'bar'
Something you could to is use Sinon's FakeXMLHttpRequest to replace your browser's XHR. It's described in this document on how to use it for testing but I'm pretty sure you can use the module for your debugging purposes.
What you need to do is:
var requests;
this.xhr = sinon.useFakeXMLHttpRequest();
this.xhr.onCreate = function(xhr) {
requests.push(xhr);
}
And then later on, you can check your requests array for headers by:
console.log(requests[0].requestHeaders);
To access your request headers.