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)
Related
I am working on javascript where i am trying to access a url path using xmlhttprequest . the code works fine with activexobject ( i dont want to use activex object ) . when i try to call it using xmlhttprequest it does not work . it gives an error saying access denied. i am using IE8 version here . I have already tried the below workaround
enabling the "access data sources across domain in internet option"
adding trusted sites
if(src) //scr = templates/mytemplate
{
try{
var xhr= new XMLHttpRequest(); //new ActiveXObject("Microsoft.XMLHTTP"); works fine
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
log.profile(src);
if(xhr.status==200||xhr.status==0)
{
//do some action
}
}
element.html(xhr.responseText);
log.profile(src);
xhr.open("GET",src,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(null);
}}catch(e){
alert("unable to load templates"+e); // here i am getting error saying acess denaied
}
Here, you got Access denied error. Looks like you are directly trying to run the HTML page in IE browser. You need to host the web page on any web server. for testing purpose, I hosted this sample page on IIS server. Than you can try to access the web page from IE will help to visit the page without this error.
I tried to make a test with this sample code and I tested it with IE 11 (IE-8 document mode).
<!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>
Output:
Based on my testing result, code is working fine with the IE-8 document mode so it should also work in IE-8 browser.
MDN tells me that the specification of the XMLHttpRequest open method includes the bstrUrl parameter and that this parameter represents "The requested URL." Vague to say the least.
www.help.dottoro.com tells me that the parameter contains the "String that specifies the URL where the request needs to be sent."
W3Schools has this example:
<!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>
This example triggers the text to be displayed when the button is clicked.
My book tells me it is "The path to the page that will handle the request." Then I see an example in my book of where a .json file is specified in that parameter which contains data that is then displayed in html.
I'm confused. How does js know what the specified file is for?
How is url parameter in open method of XMLHttpRequest used?
It's the URL that the XMLHttpRequest object will ask the browser to send the GET or POST to.
How does js know what the specified file is for?
The person writing the JavaScript writes code that knows what to do with the specified resource.
In your w3schools example, the code knows that it's requesting something that will return HTML it wants to display in the demo element.
If the request were for JSON, the code would handle a successful request by parsing the JSON and doing something with the data.
What would be the best way to get the "last modified" attribute from a file NOT on the web server. My purpose is to display the time stamps of specific network files in a web page. All the JavaScript references I have found are for the current file, or from the web server. I have found references for browsing to, drag-and-drop, etc. But I would like to read the file attribute from the original location. Is this even possible??
EDIT:
So now that I have a batch file to create the text file on the web server, how do I get that data into an array so I can display it properly? The data is correct, but it is one long string.
This is my code:
<html>
<head>
<script type="text/javascript">
function getStatus() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("backupStatus").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "file.txt", true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="getStatus()">Get QNAP Backup Status</button>
<ul id="backupStatus">
</ul>
</body>
</html>
This is my output:
#ECHO 4/13/2016 #FREEMAN1 4/13/2016 #FREEMAN02 4/13/2016 #FREEMAN03 4/7/2016 #FREEMAN4 4/7/2016 #FREEMAN5 4/7/2016 #HR10 4/13/2016 #ACCOUNTING20 4/12/2016 #IT01 4/13/2016 #PROD20 4/12/2016 #UPS10 4/13/2016
javascript can't go out and read files on a user's computer. You'd need to read this information on a server and load it in to the page, or via an ajax call.
I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation
I saw this great API (http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm) by merriam webster that returns an XML file with all the details in it including definitions and pronunciations.
This API requires a key so i registered and got a key for my account.
I am making the request using Javascript(XHR) but the status returned is zero.
Then i googled the error it said that it may be because my request is going from a "file:///" protocol instead of "http://", so i installed LAMP stack on my PC then hosted the file on my localhost server and even then no luck.
Another thread said that i cant make cross domain requests.
Please can you help me. Below is my HTML code from which i call function in my javascript file.
<html>
<head>
<script type="text/javascript" src="context-script.js">
</script>
</head>
<body>
<h1>Merriam Webster</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span><br/>
<b>Sound:</b><span id="sound"></span><br />
</div>
<script>
callOtherDomain();
</script>
</body>
</html>
Below is my JAvascript file context-script.js code:
function callOtherDomain()
{
invocation = new XMLHttpRequest();
var url = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/happy?key=8f394b2c-77e8-433d-b599-f3ca87660067';
//url="note.xml";
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
alert("ref");
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
alert("erg");
if (invocation.status == 200)
{
var response = invocation.responseXML;
document.getElementById("to").innerHTML=
response.getElementsByTagName("dt")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
response.getElementsByTagName("dt")[1].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
response.getElementsByTagName("dt")[2].childNodes[0].nodeValue;
}
else
alert(invocation.status);
}
else
dump("currently the application is at" + invocation.readyState);
}
But when i change the URL to "note.xml" which is locally stored on the localhost code works absolutely fine.
Thanks in advance.
While this question is several years old, I worked with dictionaryapi.com previously and the solution is two-fold:
Your first step to host on a local server was right on (localhost:8000 or http://127.0.0.1:8000). I prefer using the Python SimpleHTTPServer, started in the root directory of the page you're trying to host with whichever CLI tool you're most familiar/comfortable with, py -m http.server.
After that, just complete a jQuery call using ajax, get, or XMLHttpRequest—whichever you prefer. For example:
$.ajax({
url: 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/[YourWord]?key=[YourKeyHere],
method: "GET"
}).done(function(response){
console.log(response);
});