I have locally recreated an embedded-script example from the W3Schools site, but it does not work properly. It executes, creating the expected HTML page, but the onclick-activated XHR function does not alter the innerHTML content as expected. Here is the original code from the relevant page (https://www.w3schools.com/xml/tryit.asp?filename=tryxml_httprequest):
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
I've tried several things:
I created a local text file with the same name as the one being opened in the sample script, and put it in the same directory. Page loaded with button, nothing happened when it was clicked.
I added "tracers" to the script in the form of alerts to confirm the script's progression:
function loadXMLDoc() {
alert("main function successfully called");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
alert("onreadystatechange function successfully called");
alert("readyState: " + this.readyState + " " + "status: " + this.status);
if (this.readyState == 4 && this.status == 200) {
alert("readyState/status function successfully called");
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
When executed, the first two alerts appeared as expected. The third appeared twice, reflecting a change in readyState from 1 to 4, but the status remained 0 in both alerts. The fourth "tracer" alert never appeared.
I altered the final conditional to allow for "status == 0", and the fourth alert appeared, and the button disappeared...replaced by nothing.
Just to be sure, I changed it so that the string "hello world" was directly added to the innerHTML, which worked.
I tried the same variants on a different workstation (both were running Ubuntu Linux btw, and I executed the code with both Firefox and Chromium).
Obviously, the responseText is coming up empty. And presumably this is because the request failed, as evidenced by the status remaining 0 instead of changing to 200.
It would be bad enough if I couldn't get this simple code to work, but here's the hair-tearing, teeth-gnashing part: I ran this same code sample a couple of days before, and it executed flawlessly. Furthermore, I had written a much more complicated script employing my new-found knowledge of xhr to load much larger files, store their contents in variables and perform .searchs on them, also without any problems. I was in the process of elaborating the code when it failed, and at first I thought I'd made a change that "broke" it. But as I rolled it back to more and more "primitive" versions - versions I knew had worked - I discovered xhr no longer worked at all, as corroborated by formerly executable tutorial code no longer working, either.
I don't remember if there was an interim update of Firefox or Chromium that might have affected things, but that seems like a pretty weak possibility.
What am I missing?
Thanks in advance,
Rob
Related
my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it
looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>
Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.
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 started working my way through the AJAX tutorial on the W3Schools website and my first example won't even run. Why won't this run please? It opens up in the browser but nothing happens when I click the button.
The tutorial URL;
https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_ie
Here is my HTML page that I created in Notepad++
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onClick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6 and IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
I run the HTML page by selecting Run >> chrome in Notepad++ (but tried Firefox and IE too). The ajax_info.txt file is in the same location as the HTML file. Here is its contents;
AJAX is not a programming language.
AJAX is a technique for accessing web servers from a web page.
AJAX stands for Asyncronous JavaScript And XML.
you must change xhhtp.onreadystatechange instead of xhttp.onreadystatechange and xhhtp.send(); instead of xhttp.send();
function loadDoc() {
debugger;
var xhhtp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhhtp = new XMLHttpRequest();
} else {
// code for IE6 and IE5
xhhtp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhhtp.open("GET", "ajax_info.txt", true);
xhhtp.send();
}
Because of the typo xhhtp instead of xhttp.
You should read up on CORS. For example:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your can see your code working if you run a local web server, which serves the html file in question (keep the txt file in the same directory as the html file).
If you are on a mac, an easy way to run a local web server is to run the following code from where your html file is:
python -m SimpleHTTPServer 8001
then in your browser go to
http://localhost:8001/yourhtmlfile.html
Since you mentioned notepad++, seems you are not on mac, but some light googling will give you a similar setting for windows.
Thanks everyone. I installed Apache and set port to 7777 (because already had IIS on port 80) and placed files in htdocs location of apache and used the url http://localhost:7777/htdocslocation/FirstAJAXExample.html and it worked.
Using the W3School example (https://www.w3schools.com/js/js_ajax_intro.asp):
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Can someone explain why the GET action occurs after the innerHTML is set?
Logically, I'm used to languages which progress from top to bottom, working on each line of code step by step.
When I read this for the first time, I assume that the innerHTML for the demo element will be blank, and that there's no action which re-sets the innerHTML to the results from ajax_info.txt following the server request. Thinking of this in back-end languages, had the innerHTML been a variable, it would have to be updated, and the last statement might appear like this:
document.getElementById("demo").innerHTML =
this.responseText;
Example in pseudocode using variables:
var x = '' or NULL;
var y = GET text from file on the server;
var x = y;
onreadystatechange is a listener, it is not executed straight away, but listens to the XHR request for that event.
When the event is triggered, for example when the response comes back from the server, then the code will be executed.
You can also exchange the order of xhttp.onreadystatechange and xhttp.open().
The request will only be sent to the server after excuting xhttp.send().
And in xhttp.onreadystatechange=function(){} you can find
if (this.readyState == 4 && this.status == 200){
// dom excution
}
which means dom excution after xhttp.send() sending the request to the server and the readyState==4 &&status==200.
In javascript there is no guarantee that every code will be execute one after another. If some line takes time , then the second line start excution. So here if some execution precedence is required then need to apply the callbacks.For the case of Ajax follow the synch or async way.
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.