First AJAX example won't run - javascript

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.

Related

How to get the IP Adress in JS - Firefox Addon Devloment

I am building a small custom Firefox Addon with regards to the Firefox documentation. Basically it uses javascript and can also use some Firefox JS Extension APIs. I am trying to get the browser IP adress from inside the extension, usually I would use a PHP script for that but here I think I am limited to this HTML and JAVASCRIPT combination, Any ideas about this?
var xmlhttp = new XMLHttpRequest();
var url = "https://api.ipify.org/?format=json&callback=getIP";
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
var ip = myArr.ip;
console.log(ip);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
you can use HTTP Request for Getting IP Add. of your client
https://api.ipify.org this website provides you the user ip address as a json object
<script>alert(window.location.hostname)</script>
in this case an alert will pop-up but the code is inside of it

Why would XMLHttpRequest suddenly stop working?

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

Link triggering XMLHttpRequest

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.

Text file comes back empty when loading with Ajax javascript

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!

XML HTTP GET Request Fails

I'm doing a pure JS GET request, to my localhost (don't worry I tested POST and that works), I can access all the database and everything else but the GET request won't work. My JS code is shown below:
functtion getSessionKey() {
XMLHTTP = new XMLHttpRequest();
XMLHTTP.open("GET", "http://127.0.0.1:8080/projects/To-Do-App/api/sessionData/sessionKey.php", true);
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.readyState == 4) {
alert(XMLHTTP.responseText);
}
}
XMLHTTP.send(null);
}
In the PHP file I have the following code:
<?php
session_start();
if (isset($_SESSION['sessionKey']) && !empty(trim($_SESSION['sessionKey']))) {
echo htmlspecialchars(trim($_SESSION['sessionKey']));
}
?>
The POST requests all work and insert into the database, but the GET request seem to stop all the JS code below it from working. Any ideas why? I have tried changing the last parameter true/false. Also I am trying to make it for a mobile application through Intel XDK so I using JS and PHP if that helps. Please no jQuery solutions as that doesn't seem to work.
You didn't set the content type
var XMLHTTP = new XMLHttpRequest();
XMLHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
...
and try to replace
XMLHTTP.send(null);
with
XMLHTTP.send();
Don't send a null in with the .send() Make it
XMLHttp.send()

Categories

Resources