I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest.
I am trying to load the data, parse it and then store it in localStorage
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason.
Does this has anything to do with localStorage?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
There are two causes of status code of zero.
Making calls from the file protocol.
The page is refreshing/navigating away as the request is being made.
In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false.
Sounds like a caching issue. Try either switching to a POST method, or appending a timestamp to the GET request querystring and see if that prevents the caching.
xmlhttp.open("POST", "data/somedata.txt", false);
or:
xmlhttp.open("GET", "data/somedata.txt?" + new Date().valueOf(), false);
Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie: Cache-Control: no-cache
Try xmlhttp.abort() before opening a new request.
It's a long shot but worth the try.
Related
I've searched and searched and could not find a solution for this:
I'm trying to load .txt file contents with Ajax but the file comes back empty.
I checked the ready state and status. ready state is 4 which means that connection was set, data received , status is 0 which means error for loading http but I read on a forum that it is ok for a local file.
I really don't know what to do.
all help will be appreciated!
this is my code:
<script>
function load() {
var selectedValue = document.getElementById("mySelect").value;
var xhttp;
alert("in func")
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
try{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && (xhttp.status == 200 || xhttp.status == 0)) {
document.getElementById("textDiv").innerHTML = xhttp.responseText;
alert(xhttp.responseText);
}
};
if(selectedValue == "Year 1"){
xhttp.open("GET", "file://year1.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 2"){
xhttp.open("GET", "year2.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 3"){
xhttp.open("GET", "year3.txt", true);
xhttp.send(null);
}
}
</script>
The issue is most likely the file protocol: file://year1.txt
try using a relative path instead, ie ./year1.txt
Edit..
I missed this the first time around.. you will get several hits to your callback function on a successful call. You'll get one where the status is zero first, then if successful you'll get another one with a 200. Why are you checking for both?
change this...
if (xhttp.readyState == 4 && (xhttp.status==200 || xhttp.status==0))
to this...
if (xhttp.readyState == 4 && xhttp.status==200)
OK! after EXTENSIVE research the problem was the infamous cross origin request problem (which does not allow access to local files as part of a security measure to insure you don't upload infected files &ct)
the solution is :
when initializing the variable for the XMLHttpRequest write:
xhttp = new XMLHttpRequest({mozSystem: true});
(notice the {mozSystem: true} inside the request)
AND IT SOLVES THE PROBLEM!!!
Thank you for your time, I hope this helps someone :)
My previous answer worked but not for long - after I restarted my computer the ajax stopped working at started throwing the cross origin error again. so- the best option I found that also works for all the browsers I checked (chrome, IE), is to set up a local server and run it from there.
here is a link for instructions:
https://www.maketecheasier.com/setup-local-web-server-all-platforms/
Good luck!
i want to call a html online link using xmlhttprequest with javascript, here is my code
but when the code arrive to xmlhttp.open it stopped and does not continue the execution
function loadXMLDoc(size,downloadfromurl) {
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 && xmlhttp.status == 200) {
var temp = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://app.arsel.qa/mobileappspeedtest/samples/256.htm?n=" + Math.random(), false);
xmlhttp.send(null);
}
What you are doing is an actual AJAX request to that page.
Cross domain AJAX requests are not allowed by default for security reasons.
However, there are several ways of performing cross domain requests, and you could take a look at how jQuery does it, so you don't have to reinvent the wheel all over again using plain JavaScript. This article should be helpful.
Anyway, if you actually want to crawl that page, there are tons of open source libraries for server side scripting languages like Java, PHP, Node.js, etc that are very useful in gathering the content, parsing the HTML and so on, depending on your needs.
You can use JSONP for overcoming cross domain barrier.
$.ajax({
type:'GET',
dataType:'jsonp',
jsonp: "jsonp",
url:"http://yoururl.com?callback=callbackFunction"
});
function callbackFunction(data){
//you can process the data here
console.log(date)
}
I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
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 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.
I have a piece of code that works in chrome and firefox but not in internet explorer. I can't figure out what that actual cause is. I get a operation timeout message from internet explorer "Message: The operation was timed out."
This is the ajax function I am using, it's from w3schools so I know this is correct.
function ajax() {
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");
}
alert(xmlhttp);
return xmlhttp;
}
This is the code that's getting stuck on. The error message is in "ajaxRequest.send(postdata);".
function edit(){
var ajaxRequest = ajax();
var postdata = "data=" + document.getElementById("id1").value + "<|>" + document.getElementById("id2").value + "<|>" + document.getElementById("id3").value;
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('ajaxDiv');
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
alert(postdata);
ajaxRequest.open("POST","confirmPage.php",false);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(postdata);
alert("Finished");
}
All the other pages work with the same code in internet explorer but not this particular page. I can't seem to figure to out why. This page works in chrome and firefox but not in internet explorer. It never goes to "Finished". I am using IE 8.
As you require synchronous behaviour try the following:
ajaxRequest.open("POST", "confirmPage.php", false);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(postdata);
if (ajaxRequest.status === 200) {
document.getElementById('ajaxDiv').innerHTML = ajaxRequest.responseText;
}
alert("Finished");
You don't need the onreadystatechange as the request is synchronous.
Partial answer:
I figured out the problem. It's not javascript and/or ajax. IE can't handle a large number of results in queries so it times out. It's a very obscure error as I was thinking it's something to do with the ajax functions rather than the php file.
The result set is not huge. There are 5 different queries. Each one with about 5-50K records(I am not printing all of them, just querying). It times out after a large result set.
To test I created a test page with simple SELECT * queries and it can handle only 2-3 queries. If it's more than that it times out.
i am using a google map api to get location. i have used the below function onchange of address field. it is working properly onchange. i have used same function on submit in the same form to checking the function once again while submitting using a onsubmit attribute. but while submitting i cant able to get answer from this ajax because of the that return by using this return true the form submit with pout getting answer.
please any one find a solution for this
function validatePlaceForm(){
var frm = document.frmOncampus;
var oncampusAddress = frm.oncampusAddress.value;
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 && xmlhttp.status==200){
//document.getElementById("my_div").innerHTML=''
var result =xmlhttp.responseText;
//alert(result);
var both =result.split("|");
frm.oncampusLatitude.value=both[0];
frm.oncampusLongtitude.value=both[1];
}
}
var url='latlog.php?address='+oncampusAddress;
xmlhttp.open("GET",url,true);
xmlhttp.send();
return true;
}
Unfortunately this will never work because the way you're using the XHR there is asynchronous:
xmlhttp.open("GET",url,true); // true means asynchronous
As the call is asynchronous the result of the function will have no result on the running of the Ajax request.
If you want to continue with using this function just change this last parameter to false, i.e.
xmlhttp.open("GET", url, false); // will now be synchronous
You also won't need a onreadystatechange handler now. Bear in mind that this will obviously make the XHR call synchronous on your onchange event too; maybe customise the function to accept a flag for is_synchronous or something.
You might also want to consider adding a timestamp onto your requests so that the browser does not cache the response.
Change the return value from true to false and call this function like this:
onsubmit="return validatePlaceForm();"
This should do the trick.
Check for the response coming from AJAX. If response is blank then return false, otherwise return true.