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!
Related
I have made a simple XMLHttpRequest which does work, it sends request etc. Just like in W3 schools.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demox").innerHTML = this.responseText;
}
};
xhttp.open("POST", "textx.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=" + textxx);
}
The problem starts when I try to trigger the request by clicking a link, which sends me to the php file which processes the request. I find it hard to understand on my current level why it doesn't work, since it worked with simple forms and such.
I get:
"Notice: Undefined index: fname ..."
So, I assume, it means the variable wasn't sent. Can someone explain? Or is there way to debug the things that are being sent from one page to another. All I found was a debugger in chrome which indeed captures the requests, but has no real use, since I get sent to the textx.php page and all is lost.
Not really sure, where your problem might be, maybe try:
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "textx.php", true);
xhttp.onreadystatechange = function() {
if (this.readyState === 4){
if(this.status===200 || this.status===0){
document.getElementById("demox").innerHTML = this.responseText;
}
};
var fname = "fname=" + textxx;
xhttp.send(fname);
}
You might console.log(xhttp); and see the step by step profile and find out where the problem might be.
Either way, I am still not sure, but I uploaded my page(code) to a hosting server and the code worked. PHP didn't show any warnings and all went as planned. The problem it seems has to do something with running a local server(WAMP). Changing PHP version didn't help. I may need to dig a little deeper on this.
i have been trying very unsuccessfully to download a binary file from my server using jquery-ajax, which i finally gave up. so now i am trying to use XMLHttpRequest instead. however, i cannot even get a simple example working.
strangely enough, this code does not appear to do anything. i copy/pasted this from w3schools and this example is near identical to many other examples. it does not work for me in either chrome or FF:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Action to be performed when the document is read;
}
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();
we go into the onreadystatechange function only once, on the open() statement with an xhttp.readyState equal to one, but not on the send() step. i should think it would at least throw some kind of error rather than do nothing at all.
also, as an experiment, i purposely fed the open() a bad url - but again no reply.
can anybody tell me what i might be doing wrong?
thank you very much.
Your code looks correct to me, which points to some external cause.
Is your code flowing all the way through to the end of the execution context? Browsers will hold onto network requests until the engine yields back to the browser.
For instance:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Action to be performed when the document is read;
}
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();
while(true){}
will never send the call.
This question has been asked twice on these forums, but the answer provided is not working for me.
The issue is that I have JSP page which is returning and flushing small amounts of output.
I am using the following code to read the output:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 3) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "download.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('X-Requested-With', "XMLHttpRequest");
xmlhttp.send($('#submitDownloadForm').serialize());
On Firefox this works fine, and I am given 3 alerts during the duration of the process.
However, on Webkit based browsers such as Chrome and Safari, I am given the first alert, but not the other 2 until the process has completed.
Other answers have said that changing the Content-Type:text/plain or Content-Type:application/octet-stream, but if I do this, the readyState jumps straight to 4 as if the process has completed instantly.
I cannot find any solutions for this.
Any help greatly appreciated, thanks in advance everyone.
I added the following code to the JSP file just before where it produces the output, and this has resolved the issue on Webkit-based browsers:
response.setContentType("application/octet-stream");
I'm now getting the updates every time output is flushed.
Hello everyone I am building a Music download website where i offer users to download songs.
Let's disclose the whole scenario.
I have a menu where each menuItem has a link and each link has been given a unique id. Based on the link clicked, with the help of the id, I am preparing the parameter which is the absolute path for the file to be downloaded and I am retrieving this with ajax where i am getting the responsed data displayed in a table. But I am not able maniplate this data which I obtain through ajax. Please help me.
My code looks like:
I am calling this function on each menuclick which gets the absolute path for the Movie song request.
function call(i) {
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("placeholder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "./SongsDemoList.jsp?path=" + document.getElementById(i).value, true);
xmlhttp.send();
}
Now Here SongsDemoList has a anchor tag for each songs but i am unable to click the link.
plz help me..
The xmlhttp object has an attribute called the responseText, which is the text the server sent back, if any.
The onReadyStateChange function currently sets the innerHTML of an element with the id of 'placeholder', to the received text, but you can do anything to the xmlhttp object's responseText. For example, if you have a loadVideo function, which can load a video based on what the server sent back, you can call it like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
loadVideo(xmlhttp.responseText);
}
}
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.