Read a text file using XMLHttpRequest? - html

I have been trying to use the XMLHttpRequest to read a text file and display the text. The text file I is going to be linked externally. So far I have the following code
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest object</h2>
<script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", XMLHttpRequest.txt, true);
</script>
</script>
</body>
</html>
I do not see my text file showing up and I am completely lost. I looked around on stack overflow already for answers and I did not find anything.

You haven't specified where your text file is located.
Here's an example of a working XMLHttpRequest with a remote api (not a real api endpoint, just an example url). You could adapt this to use a text file instead of json. Remember to call your function in the end! findCity( city ) for instance.
function findCity(elem) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("city").value = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "https://api.example.com/api/postcodes.json?pnr=" + elem.value + '&clientUrl=http://localhost', true);
xmlhttp.send();
}

Related

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

If webpage exsits load, if not load .mht

Working in HTML/SCSS/JQUERY.
Want to link to a webpage but if it's a broken link that it will load the saved .mht version.
Another user provided this code in other thread of this forum to chek if a link is broken (JavaScript/jQuery check broken links)
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);

How to convert content of web page to json file ? Like I pass the url of page n it got converted to json file. Web page only contains json string

How to convert content of web page to json file ?
Like I pass the url of page n it got converted to json file.
Web page only contains json string.
Also you can do it with ajax
<script type="text/javascript">
function loadJSONDoc(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
document.getElementById("myBody").innerHTML = xmlhttp.responseText;
//if your response text is JSON object
document.getElementById("myBody").innerHTML = JSON.stringify(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
loadJSONDoc("your_url")
</script>
OrginalAjaxMethotHere

Couldn't make ASPJAX working

I want to make a demo on how to combine ASP and AJAX. I have found snippets from http://www.aspjax.com and implemented it in my project. However, the text that should be displayed cannot be output properly.
Here's the code. Basically the same as the one in the original:
In index.asp
<script language="javascript" type="text/javascript">
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo&param2=bar'
// FunctionName : the JS function that will handle the response
var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {
// create the new object for doing the XMLHTTP Request
var myConn = new XHConn();
// check if the browser supports it
if (myConn) {
// XMLHTTPRequest is supported by the browser, continue with the request
myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);
}
else {
// Not support by this browser, alert the user
alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");
}
}
// launched from button click
var getMessage = function () {
// build up the post string when passing variables to the server side page
var PostStr = "";
// use the generic function to make the request
doAJAXCall('ajaxtest.asp', 'POST', '', showMessageResponse);
}
// The function for handling the response from the server
var showMessageResponse = function (oXML) {
// get the response text, into a variable
var response = oXML.responseText;
// update the Div to show the result from the server
document.getElementById("responseDiv").innerHTML = response;
};
</script>
<body>
<button onclick="javascript:getMessage();">Get Message From Server</button>
<div id="responseDiv">Original Text</div>
</body>
So, the code tells it to replace the Original Text in the div with the one in ajaxtest.asp
In ajaxtest.asp
<%# Language=VBScript %>
Response.Write "The Server time is " & Now()
The problem is when I click the button Get Message From Server, the stuff in ajaxtest.asp is rendered as plain text, but not in ASP. How to fix this? Is it because of the extension used is wrong?
EDIT: by plain text I mean exactly as Response.Write "The Server time is " & Now()
You probably want the contents of your ASP page to be:
<%# Language=VBScript %>
The Server time is <%=Now()%>

Ajax html Domparser

I have some ajax code in an html doc that changes the text of a button to text stored in another html doc in the same domain. The text is in the body tag of the second html document.Like this:
<body> Text</body>
So the code makes an ajax request, parses the response to create an xmldoc. When I try to use the
getElementByTagName("body") or even getElementByTagName("html")
I get an emepty HTMLcollection. But when I use the
queryselector("body") I can get to the text. The log to console prints undefined.
Here's the full code:
function gettxt()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://localhost/ajax2.html", true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200)
{
allText = xmlhttp.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(allText, "application/xml");
var bodyobj=xmlDoc.getElementsByTagName("body");
console.log(bodyobj.lemgth);
document.getElementById("secbtn").value=bodyobj;
}
}
}
xmlhttp.send(null);
}
What am I missing? Thanks.
I know what I was doing wrong. I was setting the button's text to bodyobj instead of bodyobj[0].innerHTML.