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

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 .

Related

Input stops working when I change value (Node.js)

I just want to insert value in text input on https://hordes.io/clans website.
When you natively enter there characters, all elements load automatically. But when I do this:
document.getElementsByClassName("navbtn")[0].value += "d"
It neither loads new results nor works at all when you try to do anything manually afterwards.
In case with document.getElementsByClassName("navbtn")[0].value += "" it continues working.
I tried another method to enter values there: clicking input field - returns undefined.
Is there any way I can search on this page? By the way I did it just in chrome snippet
I think I've found a decent solution. Their website makes a post request to their api --> https://hordes.io/api/claninfo/list.
You can pass json to specify which clan you want!
Like this:
POST: https://hordes.io/api/claninfo/list
PAYLOAD: {"name":"dmdw","order":1}
RESPONSE:
{"clans":[{"name":"Darkmetal Dwarfs","tag":"DmDw","level":9,"gold":"42141","faction":0,"members":"2","prestige":"9446"}]}
You can try the request on reqbin.com following this link with already filled in params: https://reqbin.com/oieogjuu
Generated code from reqbin.com:
var url = "https://hordes.io/api/claninfo/list";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
var data = '{"name":"dmdw","order":1}';
xhr.send(data);

Javascript using sourceURL to load source files in dynamically loaded scripts

I have a few dynamically loaded JS scripts that I want to be able to debug in chrome DevTools. I have read that I should be able to achieve this by appending
//#sourceURL=someFile.js
To the source I will be using eval on.
This is what I currently have:
var loadDynamic = function(filename){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
eval(this.responseText + "\r\n" + "//#sourceURL="+filename);
}
};
request.open("GET", filename, false);
request.send();
}
loadDynamic("someFile.js");
I am getting no errors in the console log and the source is not being added to the source tree. However the evaluated code is definitely loaded and executed correctly. It is just the #sourceURL that isn't getting picked up.
Am I using this correctly?
Thanks

Get innerHTML from XMLHttpResponse

I'm trying to write a chrome extension that will get a value from a current page, then use that information to go to another page and pull a specific element from the html response. I can get the html response fine, but I'm unable to parse the html response to get the specific element.
content.js
function getTicketInfo(){
var ticketURI = document.getElementById("p3_lkid").value;
var ticketNumber = document.getElementById("p3_lkold").value;
var xhr = new XMLHttpRequest();
xhr.open('GET',"remotePage.html",true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
function handleResponse(xhr)
}
}
xhr.send();
}
function handleResponse(xhr){
var contactElement = xhr.getElementById("CF00N80000005MAX6_ileinner");
alert(contactElement.clildNodes[0].nodeValue);
}
remotePage.html
<html>
<div id="CF00N80000005MAX6_ileinner">
Text I need!
</div>
</html>
How can I get this value from the external page? Is there a better way to request this information?
Your XHR response is a string, and not a DOM.
With jQuery you'll be able to convert it to a DOM, and query it.
function handleResponse(xhr){
$(xhr.response).find('#CF00N80000005MAX6_ileinner')
}
This is as simple as not parsing the HTML response to a DOM object. According to MDN, this is how you parse XML (Or HTML, and with Vanilla JavaScript):
var parser = new DOMParser();
var doc = parser.parseFromString(xhr, "text/xml");
And then using the new DOM Object doc for accessing elements.
var contactElement = doc.getElementById("CF00N80000005MAX6_ileinner");
alert(contactElement.childNodes[0].nodeValue);
I also noticed you spelled childNodes wrong, but that isn't the main problem.

Get Raw Gist File [duplicate]

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.

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