Get Raw Gist File [duplicate] - javascript

This question already has answers here:
Pull in JSON data
(3 answers)
Closed 6 years ago.
What I want is simple. Is there any way (including a work around) to make this work?
function loadXMLDoc() {
var request = new XMLHttpRequest();
var gistRawFileUrl = 'https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md';
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var gistFileContent = request.responseText;
doSomethingCool(gistFileContent);
}
};
request.open('GET', gistRawFileUrl, true);
request.send();
}
Right now, if I execute this in the console here I'm getting:
XMLHttpRequest cannot load https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
This makes sense, and I know I'm not going to get GitHub to open up their access control, but if there's a work around to this or if I'm doing something wrong that would be great.
I realize that you can get the content of the file, by hitting the JSONP endpoint, but that doesn't give you the newline characters, so what was once this:
Hello World!
You
Rock!
Is now this:
Hello World!YouRock!
Thanks in advance.
Edit The problem with the newlines is something I need to fix on my end, not a Gist thing.

Check out this answer: https://stackoverflow.com/a/10454873/240963
API endpoint will give you content of each file within the Gist, including the formatting. The only downside is that you need to transfer extra data even if you already know the URL for the raw file.
We can simplify the code from the original answer, since you don't want to parse JSON and you probably know the filename:
$.ajax({
url: 'https://api.github.com/gists/'+gistid,
type: 'GET',
dataType: 'jsonp'
}).success( function(gistdata) {
var content = gistdata.data.files[filename].content;
DoSomethingWith(content)
}).error( function(e) {
// ajax error
});
JSFiddle
Using JSONP with raw XHR is a bit more complicated, but you could use something lighter than jQuery.

Related

vanilla js equivalent to "Loading Page Fragments" via XMLHttpRequest by div id

For learning purposes, trying not to use jQuery to get remote content.
The following snippet works well. It fetches two divs and puts them in the current page.
It's fetching this raw gist:
<div class="remote" id='one'>one</div>
<div class="remote" id='two'>two</div>
function remoteFetch() {
var xhr = new XMLHttpRequest();
var varUrl = 'https://gist.githubusercontent.com/persianphilosopher/b0d4e948da801d09969b4ac6f5c0206d/raw/d139dd28e2cd5a73a4b38f489c8462c755c342c6/temp';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status == 200) {
document.getElementById("here").innerHTML = xhr.responseText;
}
}
}
xhr.open("GET", varUrl, true);
xhr.send();
}
remoteFetch();
<div id="here"></div>
Question: What I cannot figure out is the equivalent of the following jQuery bit:
$("#here").load("varUrl #one");
that would allow me to only fetch a div by its id.
The closest I found on SO is this answer but I failed to adapt it here for my needs.
Thanks in advance.
The implementation in your codepen almost works, there's two issues which I've rectified in this fork:
https://codepen.io/anon/pen/VdJYVG?editors=1010
First issue was a typo on svgDoc.getElementsById, it should just be svgDoc.getElementById.
Second issue was a parsing issue in the DOMParser. You are passing in text/xml as the expected MIME-type while the content you want to parse is text/html .

How can I read the contents of a .txt file and store it to a global variable using Javascript? [duplicate]

This question already has answers here:
HTTP GET request in JavaScript?
(31 answers)
Closed 6 years ago.
I have:
var datahere;
var url = "/example.txt"
example.txt has the text "Hello World"
How do I get datahere to equal this string outside of any request?
I'm happy to include PHP into the equations if necessary.
Like #J.T. Crowder said, your question is not very specific about your scenario. You can also find plenty of websites explaining in great detail how XMLHttpRequests work. What you want can be achieved with a simple request like this:
var result, url = "/example.txt";
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.onreadystatechange = function(e) {
if(xhr.readyState == 4 && xhr.status == 200) {
result = xhr.responseText;
document.writeln(result);
}
};
xhr.send();
This specific script will run under any webserver, but it won't run if you open it locally.
Here's one of those websites that explain everything https://xhr.spec.whatwg.org/

How to receive data from XMLHttpRequest in chome extension via javascript?

I wanna to send request form a webpage to chrome extension, and then in chrome extenison receive data and read data, is there any way to this?
Ex:
In doman www.nope.com/sendRequest.html will sent data to chrome extension via url chrome-extension://xxxxxxx/getData.htm?isToken=abc, and then extension will receive and can read data "isToken".
Here is my code in sendRequest.html
<script type="text/javascript">
function sendRequest() {
document.write("Sending request");
var req = new XMLHttpRequest();
req.open("POST", "chrome-extension://xxxxxxxxxx/getData.htm?isToken=abc", true);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
document.write("OK");
}
}
};
req.send();
}
</script>
And in chrome extension file getData.htm, how can I get data?
(Edit: what type of data are you sending? Could you pass it through as a JSON encoded string, via GET? JSON.stringify() and JSON.parse() may be of use to you. :)
The following may be useful as a guide for accessing that POST/GET data. :) )
As far as I am aware, this is best done using some form of server side scripting. You could use window.location.search in JS, and split the string and perform the necessary functions, but I think server-side scripting may work best. :)
An example of a JS implementation could be as follows:
var url = window.location.search;
var params = url.substr(url.IndexOf("?") - 1, 30);
This would grab the parameters (starting at ? (inclusive), and continue for 30 chars. You could also use something like var params = url.substr(url.IndexOf("?") - 1, url.length); to get the whole parameters list.
How you use this from then on, is up to you, but you could pass it through a switch() or whatever you need. :)
Obviously, this being a chrome extension would limit your options regarding any server-side processing. :/
Edit: The above would go in getData.htm. :)

Json problem in fetching data

<script>
function jsonfunc(){
var data ="publick="+document.getElementById("publickeyval").value+"&privatek="+document.getElementById("privatekeyval").value;
var url="http://www.remoteapiserver.com/example_api/example_adcpatchaapi.php?"+data;
alert(url);
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if (http_request.readyState == 4){
alert(http_request.responseText+"#"); // showing only # //
my_JSON_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
}
</script>
I was as asked my question as per comment i read Json and writing above code in my php page.But still this is giving problem.I am not getting fetched dada from remote server.I am getting only "#" in alert box.
I highly recommend a JavaScript Framework like jQuery for this kind of stuff. It definitely makes this a lot easier. jQuery lets you do cross-domain requests, if you use JSONP (take a look at the docs). The code would look something like this:
$.getJSON(yourUrlGoesHere, function(data) { // ready callback
// data is an object; no need to parse it manually.
});
Sometimes it't better use some library:
JQuery or Moootools: http://mootools.net/docs/core/Request/Request.JSON
Implement this in native JS is difficulty if we want use it in all browsers ;)

What is the best method to detect xml in JavaScript

What is the best method to detect xml in JavaScript
e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.
this needs to work in Chrome.
thanks,
Josh
If you are using XMLHttpRequest to get this data, then you can simply check for the Content-Type header using the getResponseHeader method (granted that the server sends the appropriate headers).
var getFile = function(address, responseHandler) {
var req = new XMLHttpRequest();
req.open('get', address, true);
req.onreadystatechange = responseHandler;
req.send(null);
}
var responseHandler = function(resp) {
if ( this.readyState < 4 ) { return; }
console.log(this.getResponseHeader("Content-Type"));
};
getFile("http://zebrakick.com/some/file", responseHandler);
(I seem to be using this code sample a lot...)
You can't determine what the mime-type is with Javascript. I would recommend doing checks on the data returned to see if it is valid XML before you try to parse it. (I'm only assuming what you're trying to do. I can provide a more rigid example if you clarify what your goal is.)
I came across this when looking to determine that a chrome extension script was on an XML page. Maybe this saves someone a few minutes.
In the chrome console and content scripts you can check with:
document.contentType==="application/xml"

Categories

Resources