I'm practicing XmlHttpRequest, and I'm trying to run basic Javascript that will get the data stored in a text file. Here's my Javascript:
var xml = XMLHttpRequest();
xml.open("GET", "setverfile.txt",true);
xml.send(null);
alert(xml.responseText);
And my html:
<!DOCTYPE html>
<html>
<head>
<title>XMLHttpRequest</title>
</head>
<body>
<script src="XMLHttpRequest.js" type="text/javascript"></script>
</body>
</html>
textfile:
This is a textfile resideing on a server
When I try running the code, nothing happens. What am I doing wrong?
Seems like you're missing your [onreadystatechange]
When you send an Ajax request, you need to listen for the state change.
Your code is asynchronous, hence listening for state change is required.
xml.open("GET", "setverfile.txt",true); // The true parametter is for async
If you did
xml.open("GET", "setverfile.txt",false); // The false parametter is for non async.
Then your code should work.
In my testing, it seems that all you were missing was the new keyword:
var xml = new XMLHttpRequest();
Related
this is the simplest code I have written and backend there is simple php api which recieves a get paramter and stores it.
<!DOCTYPE html>
<html>
<head>
<title>
test beforeunload
</title>
</head>
<body>
<script type="text/javascript">
function httpGetAsync(data){
theUrl='http://niteshchaudhry.com/ajay/api.php?name='+data;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET",theUrl, true);
xmlHttp.send(null);
}
function fireAsap(){
var elem=document.createElement('script');
elem.src='http://niteshchaudhry.com/ajay/api.php?name='+new Date();
document.getElementsByTagName('body')[0].appendChild(elem);
}
window.onbeforeunload = function(e) {
fireAsap();
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};
</script>
</body>
</html>
problem is I have observed in database which shows me 1 entry after two refresh or unloads irrespective of which function I use fireasap or httpgetAsync. can anyone explain what is wrong or what can be done to get the data every refresh or unload
Have a look at navigator.sendBeacon(), it's designed for exactly this use case.
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
The problem with regular requests is that there's no guarantee that the browser actually manages to send the request before the page gets unloaded, it's done on a 'best effort' basis. navigator.sendBeacon() tells the browser to perform a request in the background, separately from the actual page instance. These requests are always POST requests so you'll have to change your server end-point to act on POST instead of GET requests.
navigator.sendBeacon() is not yet universally supported so you'll need to use a regular request as a fallback solution.
I know I might just be missing a simple thing that's right under my nose, or may not understand ajax at all... but I have a problem - this simple peace of code isn't working, but it's from w3schools and it's the simplest example of ajax working.
Can someone help me, please?
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Here's the "ajax_info.txt" file:
text changed.
If you're opening the file in the browser with file:// or C:/ protocol you'll get a cross origin request error when trying to load 'ajax_info.txt', the reason for this is to protect your machines private files from being read by browser scripts. To fix this you'll need to use the protocol http:// which you can do if you install a webserver onto your local machine such as WAMP or MAMP.
Additionally a file called ajax_info.txt needs to exist in the same directory as this html file. Otherwise this javascript AJAX call will return an error: /ajax_info.txt 404 (Not Found)
I'm new to node and am practicing making http requests using the request module. In my script, when the user presses a button I want its callback function to make a request which gets the HTML from a webpage and filters it to get an array of data.
My server request works by itself, but when I try to combine it with HTML nothing seems to happen. My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="test1.css" />
<script src = "posts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<p id = "myText">Hello, this is dog</p>
<button onclick="getPosts()">Get Posts</button>
</body>
</html>
and posts.js is this:
var request = require('request');
function getPosts(){
alert('Hello');
var matches = [];
request('https://www.reddit.com/r/TagPro/top/?sort=top&t=all', function (error, response, body) {
// Handle errors properly.
if (error || response.statusCode !== 200) {
return res.writeHead(error ? 500 : response.statusCode);
}
// Accumulate the matches.
var re = /tabindex="1" >(.+?)</g;
var match;
while (match = re.exec(body)) {
matches[matches.length] = match[1];
}
$("#myText").text(JSON.stringify(matches));
});
}
On the button press, "Hello" gets alerted but nothing happens after that it seems. Is this the proper way to link up node with front end or am I approaching this the wrong way?
If you're running this in the browser then the problem is that you cannot use Node packages in the browser without some extra tooling.
If you check your console, you'll probably see something about "require" being undefined.
You should either read up on how to use tooling like Webpack (or Browserify) to make your Node packages available in the browser.
If you want to stay simple, don't use the Node requests library for client-side (browser) code. Just read up on how to make regular Ajax requests using jQuery or the native XMLHttpRequest API.
You can just replace your request call with something like
$.get('http://someurl.com', function (data) { // stuff });
I am trying to learn how to read into a web page data in an XML file. This is a static HTML page. I do not want a web server and I cannot use Ajax. The XML file is local (in the same directory as the HTML file). I want this to work in a Chrome browser.
What I need to do is:
Read the XML file on the page onLoad event.
Use innerHTML to insert the XML data into a div.
My problem is in reading the XML file. All of the examples I have found I think will only work if there is a web server running, which I have to avoid.
If you're reading another file the only way to do that with front end JS is another request (ajax). If this were node.js it would be different because node can access the filesystem. Alternatively if you get the xml into a javascript string on the same page, you can manipulate it. There are a number of good libraries (jquery's parseXML).
Original answer here: https://stackoverflow.com/a/48633464/8612509
So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!
Since you're only targeting Chrome, you could take a look at the File API. You'd have to prompt the user to select the file or drop it into a specific area of the page though, which might be something you'd rather avoid, or not. The following HTML5 Rocks article should help.
Assuming the HTML, XML and browser are all on the same machine, you might try using an Iframe in the HTML that references the XML using a URL like file:\.
You could do something like this:
<html>
<head>
<script type="text/javascript">
//If using jQuery, select the tag using something like this to manipulate
//the look of the xml tags and stuff.
$('#xframe').attr('style', 'thisxmltag.....');
</script>
</head>
<body>
...
<frame id="xframe" src="the_xml_doc"></src>
</body>
</html>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", file_Location, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(your_div_id).value =
xmlDoc.getElementsByTagName(The_tag_in_xml_you_want_to_display)
[0].childNodes[0].nodeValue;
Works with IE11
<head>
// To be hidden with a better method than using width and height
<OBJECT id="data1" data="data.xml" width="1px" height="1px"></OBJECT>
// to work offline
<script src="lib/jquery-2.2.3.min.js"></script>
</head>
<body>
<script>
var TheDocument = document.getElementById("data1").contentDocument;
var Customers = TheDocument.getElementsByTagName("myListofCustomers");
var val1 = Customers[0].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise.
Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in firebug.
UPDATE: I removed the checking of the http status returned so that code immediately goes to print the output from the server
<html>
<head>
<title>Javascript example 1</title>
<script type="text/javascript">
function doAjax()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
alert("response text: "+xmlhttp.responseText+"\n"
+"response XML: "+ xmlhttp.responseXML);
if (xmlhttp.responseText!="") {
$("thediv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://127.0.0.1/test/",true);
xmlhttp.send();
}
function $(element){
return document.getElementById(element);
}
</script>
</head>
<body>
<input type="button" value="click me" onClick=javascript:doAjax()>
<br/><br/>
<div id="thediv">
some test
</div>
</body>
</html>
my views.py
from django.http import HttpResponse
def test(request):
response_string="hello"
return HttpResponse(response_string,mimetype='text/plain')
my urls.py
from django.conf.urls.defaults import *
from project1.views import test
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^test/$', test)
# Example:
# (r'^project1/', include('project1.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
UPDATE
Here is the code in action
I just tested your code. When I clicked the "click me" button, a request was indeed made to the test view. I was able to confirm this. However, unlike what you said the view is returning the HttpResponse. To verify this yourself, access the http://localhost:8000/test/ url using your web browser. See what happens.
At first blush your problem seems to be JavaScript related. I don't know what exactly is going wrong but I'll try to debug the JS code and see.
Update
I was able to confirm that the error is indeed with the JavaScript that you are using. I found two errors. First:
if (xmlhttp.readyState==4 && xmlhttp.status==0)
Shouldn't the status be 200? So I changed it to:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
Update 2
Found that I missed the $ function.
The problem is that there are two if conditions. When first evaluates to true, the contents of the div are indeed updated to "hello". However the second if (xmlhttp.responseXML!="") also evaluates to true (null is != "", hence) and wipes out the contents of the div.
Its good to use core JavaScript when learning but you should definitely use some framework such as jQuery or Prototype as you progress. Frameworks allow to keep your code concise, develop faster and also insulate you from the cross-browser compatibility issues.
Using jQuery your code would have been something like this:
<html>
<head>
<title>Javascript example 1</title>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
<script type="text/javascript">
function doAjax()
{
$.ajax({
url: 'http://localhost:8000/test/',
success: function(data) {
$('#thediv').html(data); //jQuery equivalent of document.getElementById('thediv').innerHTML = data
}
});
}
</script>
</head>
<body>
<input type="button" value="click me" onClick="javascript:doAjax()"/>
<br/><br/>
<div id="thediv">
some test
</div>
</body>
</html>
Since jQuery provides with a default $() function, you do not need to define them in your code in case you use the framework.
Though this answer is slightly off-track, I hope it will be useful to you.