Retrieve HTML of ReadMe - javascript

Hi so first time working with APIs like this. Anyways, I've been reading up on the GitHub API and came across this:
READMEs support custom media types for retrieving the raw content or rendered HTML.
src: https://developer.github.com/v3/repos/contents/#get-the-readme
Which I believe means that it is possible to retrieve an HTML formatted version of the contents of the README? If so how would I retrieve it using AJAX since the tutorials are all for curl. In the end I want to display a portion of it on my website and would be a lot easier if given in the html format rather then markdown.
The docs say something about: application/vnd.github.VERSION.html
I just don't necessarily know how to use it.
Thanks!

You have to set the Accept header of the HTTP request to application/vnd.github.html.
$.ajax({
url: 'https://api.github.com/repos/just95/toml.dart/readme',
headers: { 'Accept': 'application/vnd.github.html' }
}).done(function(data) {
alert(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

All you need to do is set the Accept header of your HTTPS request. Using cURL for example:
curl -i -H "Accept: application/vnd.github.v3.html" https://api.github.com/repos/github/developer.github.com/readme
In JavaScript,
var apiRoot = 'https://api.github.com';
var myUser = YOUR_USER_HERE;
var myRepo = YOUR_REPO_HERE;
var request = new XMLHttpRequest();
request.open('GET', apiRoot + '/repos/' + myUser + '/' + myRepo + '/readme');
request.setRequestHeader('Accept','application/vnd.github.v3.html');
/* add event listeners... */
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
document.body.innerHTML = request.response;
}
};
request.send();

Related

Translate curl to Javascript ajax code

How can I translate this curl script to an AJAX request in JavaScript?
curl -X POST
-d "grant_type=password&username=admin&password=Demo1234"
-u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth
I will show an example in pure JavaScript
function sendData()
{
var formData = new FormData(); //create formData object to send data
formData.append("grant_type, "password"); //via append you add data
formData.append("username", "admin");
formData.append("password", "Demo1234");
var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
xmlHttp.onreadystatechange = function() //monitor status of response
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
{
console.log(xmlHttp.responseText); //then output data
}
}
xmlHttp.open("POST", "http://<host>/url/to/auth");
xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
xmlHttp.send(formData);
}
Your curl call uses three things:
Unprocessed data.
HTTP Authentication.
Templating? - Not sure.
This is what I best came up with:
$.ajax({
"url": "http://<host>/url/to/auth",
"data": "grant_type=password&username=admin&password=Demo1234",
"processData": false,
"beforeSend": function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
}
});
Replace your <ClientID> and <ClientSecret> with the right values.
Here is how you can do it for any curl not just this one:
Get postman (https://www.getpostman.com/)
follow this to import your curl to postman: https://www.getpostman.com/docs/postman/collections/data_formats#importing-postman-data
follow this to generate a code snippet for the curl you just imported: https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets
one of the code snippet exporters is jqueryAjax.

Can't Access to API using jQuery

I am using pCloud Api to get download link form the request. It is a GET request. When I request form browser I can get a response. But when I use jQuery I get a response code result : 7010
Api Request URL : https://api.pcloud.com/getpublinkdownload?code=8eM7
I get this response when requesting from browser:
{
"result": 0,
"expires": "Mon, 07 Aug 2017 00:12:50 +0000",
"dwltag": "aftsTab2SLkC4MDXRdp6Am",
"path": "\/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7\/image%20%286%29.jpg",
"hosts": [
"p-def2.pcloud.com",
"c166.pcloud.com"
]
}
I need this hosts and path to generate the download link. I just need this -https://c166.pcloud.com/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7/image%20%286%29.jpg
I have to use jQuery/JavaScript to get this response. I tried PHP file_get_contents(); it works but this link will work only form the ip address you request for. So, I must use JQ/JS.
My Code:
$(document).ready(function(){
function httpGet(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
console.log(httpGet("https://api.pcloud.com/getpublinkdownload?code=8eM7"));
});
Thanks for trying to help me.
It seems pCloud server is checking referrer.
In most case, servers will refuse the accesss not coming from itself.
Only web browsers arriving from a small set of approved (login) pages are given access; this facilitates the sharing of materials among a group of cooperating paysites from https://en.wikipedia.org/wiki/HTTP_referer
In following html, script ran and got image url successfully, but browser raised error when it was trying to load image.
<html>
<head>
</head>
<script
src="http://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<body>
<h1>Load Image from pCloud </h1>
<img class="loading">
<script>
$(document).ready(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText){
var host = JSON.parse(this.responseText).hosts[0];
var path = JSON.parse(this.responseText).path;
}
$(".loading").attr("src", "https://" + host + path);
}
};
xhttp.open("GET", "https://api.pcloud.com/getpublinkdownload?code=8eM7", true);
xhttp.send();
});
</script>
</body>
</html>

How to pass Django csrf token in AJAX (without jQuery)

Based on the w3schools ajax example I am trying to make a delete call and then remove the corresponding row from a table. There are plenty of answers here about how to do it using JQuery but I am not doing that. I found this answer which made me write my JavaScript like this:
function deleteFullLicense(rowid, objectid) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 204) {
row = document.getElementById(rowid);
row.parentNode.removeChild(row);
}
else {
window.alert("Something went wrong. The delete failed.");
}
};
xhttp.open("POST", "deleteLicense/" + objectid, true);
xhttp.send({'csrfmiddlewaretoken': '{{ csrf_token }}'});
}
But I get the Forbidden (CSRF token missing or incorrect.) message. How should I send the token?
Turns out if I called it X-CSRFToken instead it worked. Found out about it here if you want to read more.
function deleteFullLicense(rowid, objectid) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 204) {
row = document.getElementById(rowid);
row.parentNode.removeChild(row);
}
};
xhttp.open("POST", "deleteLicense/" + objectid, true);
xhttp.setRequestHeader("X-CSRFToken", '{{ csrf_token }}')
xhttp.send();
}
The header name X-CSRFToken actually comes from the parameter CSRF_HEADER_NAME in Django settings.py. When receiving frontend request (e.g. ajax call), Django internally checks header parameters and converts X-CSRFToken to HTTP_X_CSRFTOKEN which is default value of CSRF_HEADER_NAME .
The better approach would be to :
convert the value of CSRF_HEADER_NAME
render the converted value in previous step, to the HTML template
in the frontend code (e.g. the HTML template or separate js file), create a custom header with that value and the CSRF token on each ajax call for form submission.
Here's a quick example :
In settings.py
CSRF_HEADER_NAME = "HTTP_ANTI_CSRF_TOKEN"
In the view function of views.py
from django.conf import settings
from django.http.request import HttpHeaders
prefix = HttpHeaders.HTTP_PREFIX
converted = settings.CSRF_HEADER_NAME[len(prefix):]
converted = converted.replace('_','-')
# so the value HTTP_ANTI_CSRF_TOKEN is converted to ANTI-CSRF-TOKEN,
return Response(context={'custom_csrf_header_name':converted})
In your HTML template (not good practice, since this is just quick example)
<script>
// Note that the value is 'ANTI-CSRF-TOKEN'. when this header name goes to
// backend server, Django will internally convert it back to 'HTTP_ANTI_CSRF_TOKEN'
var custom_csrf_header_name = "{{ custom_csrf_header_name }}";
// the ajax part is almost the same as described in the accepted answer
...
xhttp.setRequestHeader(custom_csrf_header_name, '{{ csrf_token }}')
...
</script>

Load and display js, py, (etc...) files with JavsScript

I'm building a static website which will relay only on client-side (no PHP).
I have couple of js and py files, which I would like to display on the site as a code.
I really want to avoid using jQuery and implement everything in JavaScript (lightweight as possible).
var codeToDisplay = "<object type='text/html' data='problem001.js'></object>";
document.getElementById('code').innerHTML = codeToDisplay;
This doesn't work. What are my options?
Thanks.
Use AJAX to get the contents of the file and insert it into the element. Use .textContent to prevent interpreting it as HTML.
var url = 'problem001.js';
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
document.getElementById('code').textContent = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.send();
<div id="code"></div>

Authenticated AJAX File Download

I'm integrating an intranet with a document management system. The DMS has a SOAP API. We've built a client that receives REST calls, makes the SOAP calls, and returns JSON or document data.
The problem is all of the solutions for AJAX filedownload seem to use iFrame (see John Culniver's filedownload plugin).
I can't use this because I need to provide authentication credentials in the header. The only other potential solution I can think of is using window.open (if I can get past browser popup blocking).
Does anyone have another potential solution or how might do this with window.open??
Thanks
I don't think there is a client-side solution for this problem. window.open isn't going to let you set the request headers. You'll need to do something like send a cookie or some other value to the server and add server-side code that alleviates the need for the request header.
See the answers to:
Offer a generated file for download from jQuery post
How to set a Header field on POST a form?
I was able to do it successfully. I'm my example I'm using Basic Authentication however you can replace your Authorization header with different value (e.g you can replace it with Bearer Yourtokenvalue.
Here is the code snippet
$(document).on("click", "#btn", function() {
var username = "yourUserNameForBasicAuthentication";
var password = "yourPasswordForBasicAuthentication"
console.log("button clicked");
var request = new XMLHttpRequest();
request.open("GET", $("#txtUrl").val().trim(), true);
//Set the authorization headers
request.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
//Set the Response type as blob which means raw data
request.responseType = "blob";
//We will initiate a default file name in case no file name is detected later on from headers of HTTP Request
var fileName = "unnamed.pdf";
request.onload = function(event) {
if (request.status == 200) {
console.log("success response received");
var blob = request.response;
//Getting contenttype from response headers
var contentType = request.getResponseHeader("content-type");
if (contentType == null) {
contentType = "application/pdf";
}
//Check 'Content-Disposition' header to get filename of file (if possible)
if (request.getResponseHeader("Content-Disposition")) {
var contentDisposition = request.getResponseHeader("Content-Disposition");
fileName = contentDisposition.substring(contentType.indexOf("=") + 1);
}
if (window.navigator.msSaveOrOpenBlob) {
// Internet Explorer
window.navigator.msSaveOrOpenBlob(new Blob([blob], {
type: contentType
}), fileName);
} else {
var el = document.createElement("a");
document.body.appendChild(el);
el.href = window.URL.createObjectURL(blob);
el.download = fileName;
el.click();
el.remove();
window.URL.revokeObjectURL(el.href);
}
} //end of Status code
else {
alert("System failed to authenticate");
}
} //End of event
request.send();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="https://yoursamplefile.txt" id="txtUrl" style="width:100%" /><br />
<input type='button' value='Download File' id='btn' />

Categories

Resources