I see this code in other website but I do not
understand the specific cFunction and url
function loadDoc(url, cFunction) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseText;
}
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc('ajax_info.txt', myFunction)">Change Content</button>
</div>
In the code you posted there is a function loadDoc that takes as sercond argument another function, the callback cFunction.
loadDoc, as the name says, loads a document from the internet, identified by the url argument, using ajax. When the document is loaded the cFunction function, passed as argument, is called passing the reference of the current XMLHttpRequest.
All the stuff loadDoc do, are done when the user clicks on the button, the document that have to be loaded is ajax_info.txt and the callback function is myFunction
So myFunction is called by loadDoc when the document is downloaded with the XMLHttpRequest object that contains the response, as argument, so myFunction can read the response and print it on an HTML element.
In modern browsers you can use JavaScript debugging tools like console.log and the debugger statement
Related
In my below code, I tried to stimulate how each statement gets executed line by line while processing synchronous ajax requests. I have sent two ajax requests synchronously introducing a delay between two requests. The problem is i'm getting "Request 1" in console but not getting the response text in my dom. After delay ends, and my second request ends, the first responseText is displayed and then second responseText is displayed in my dom.
Why My first ajax response text getting late to update in my dom, even though I got a response from server-side before the delay gets start?
index.html
-----------
<!DOCTYPE html>
<html>
<body>
<!--Calls the function synchronously(async=0/false) -->
<button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button>
<p id="result1"></p>
<p id="result2"></p>
</body>
<script type="text/javascript">
function loadDoc(url) {
console.log("Entered ");
ajax(1,url,"result1");
for(i=0;i<1000000000;i++){}
ajax(2,url,"result2");
console.log("Exit");
}
function ajax(requestNo, url, div) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(div).innerHTML = this.responseText;
console.log("Request " + requestNo);
}
};
xhttp.open("get", url, 0);
xhttp.send();
}
</script>
</html>
ajax_info.txt
--------------
This is the content from a txt file.
I think there is something wrong with your response. I used a publicly available fake endpoint to reproduce this, but it works as expected:
https://jsbin.com/kojowaneda/1/edit?html,js,console,output
The only diff between this code and yours, is the parameter of the function call:
<button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>
Also, you should use setTimeout for a timeout instead of a for loop.
The first part works fine, this means the WKWebview object is able to call the java script function. The problem lies in the javascript code, I assume.
The javascript function, which is called, is supposed to read simply out of a text file in the app's bundle (fileName = "data.txt"). It looks like this:
function readTextFile(fileName)
{
var rawFile = new XMLHttpRequest();
rawFile.onreadystatechange = function()
{
if(rawFile.status == 4)
{
document.getElementById("demo").innerHTML = this.responseText;
}
}
rawFile.open("GET",file,true)
rawFile.send()
}
The output is always empty. Now I am sure that rawFile status reaches 4, I checked that. I have replaced the fileName with some make-believe non existent file and the rawfile status still reaches 4. So now I am not even sure whether the file has been found.
Is there a way to determine whether the file was found?
If it is found how can I read out of it?
I am not an experienced java script developer at all. So it might be some obvious problem. The javascript function I wrote with help of w3schools.com.
Thanks.
I think you have some formatting issues with your code and you aren't adding an event listener. Try the below. Also there is better documentation at MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function readTextFile() {
document.getElementById("demo").innerHTML = this.responseText;
}
function getTextFile(file) {
var req = new XMLHttpRequest();
req.addEventListener("load", readTextFile)
req.open("GET", file, true)
req.send();
)
getTextFile('example.txt')
<div id="demo">
</div>
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.
I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is.
I have to parse an XML file and assign its contents to the webpage - here's my code:
<script = "text/javascript">
window.onload = onPageLoad();
var questionNum = 0;
function onPageLoad(questionNum) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","quiz.xml");
try {
xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown
} catch(err) {
document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
}
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it does not run this far.
}
</script>
My XML file is inside the same directory.
<question>
<query>what is 2+2?</query>
<option>4</option>
<option>5</option>
<option>3</option>
<answer>4</answer>
</question>
Just for reference, I typically program in C# or Java, and I'm running my website on Google Chrome.
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
I see 2 possible problems:
Problem 1
the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it
Solution:
assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
Problem 2
the XMLHTTPRequest object does not exist in all browsers (by that name)
Solution:
Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}
I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is.
I have to parse an XML file and assign its contents to the webpage - here's my code:
<script = "text/javascript">
window.onload = onPageLoad();
var questionNum = 0;
function onPageLoad(questionNum) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","quiz.xml");
try {
xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown
} catch(err) {
document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
}
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it does not run this far.
}
</script>
My XML file is inside the same directory.
<question>
<query>what is 2+2?</query>
<option>4</option>
<option>5</option>
<option>3</option>
<answer>4</answer>
</question>
Just for reference, I typically program in C# or Java, and I'm running my website on Google Chrome.
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
I see 2 possible problems:
Problem 1
the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it
Solution:
assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
Problem 2
the XMLHTTPRequest object does not exist in all browsers (by that name)
Solution:
Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}