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
}
}
Related
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>
I'm trying to write a JavaScript function that gets a foreign url, and attempts to verify its existence within 'tmOut' msecs. If verified within this timeframe, it should call a 'callback' function with this url as an argument.
Here is the function:
function chkUrl(url, tmOut, callback) {
var abortChk = false;
var abortTmr = setTimeout(function(){abortChk = true;}, tmOut);
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4) {
if (x.status < 400 && !abortChk) {
clearTimeout(abortTmr);
callback(url);
}
}
};
x.open('GET', url, true);
x.send(null);
}
Problem is because of cross-domain calls (probably) I get x.status=0 regardless of the url existence.
Is there a way to overcome/workaround the problem (without the users having to modify any default browser settings)? Alternatively, is there a way to achieve the same functionality otherwise?
Is this function "reentrant"? (can I call it safely several times for different urls at once?)
Is there a way to overcome/workaround the problem
Client side? Only if the sites you are making the request to use CORS to grant you permission (which seems unlikely given the context).
Perform your test from your server instead of directly from the browser.
Is this function "reentrant"? (can I call it safely several times for different urls at once?)
Yes. You aren't creating any globals.
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
}
}
Suppose I have
1)
a HTML document.
2)
This HTML document loads Javascript file "code.js" like this:
<script src="code.js">
3)
User clicks button which runs "fetchdata" function in "code.js",
4)
"fetchdata" function looks like this:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
myjsdata = xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'http://www.example.com/data.js', false);
xmlhttp.send(null);
...
Now how do I do the following successfully:
I want to insert/eval my Javascript in a way, so all functions in "code.js" including "fetchdata" and functions defined above/below can access the data (structures, declarations, pre-calculated data values etc.) in "data.js".
(If this was possible, it would be idea since I could wait loading the actual JS data file until the user explicitly requests it.)
jQuery always has something for everything:
http://api.jquery.com/jQuery.getScript/
Loads a javascript file from url and executes it in the global context.
edit: Oops, didn't see that you weren't using jQuery. Everyone is always using jQuery...
Just do:
var scrpt = document.createElement('script');
scrpt.src='http://www.example.com/data.js';
document.head.appendChild(scrpt);
i think you should take a look at this site
this site talks about dynamic loading and callbacks (with examples) - where you can call a function in the loaded script after it loads. no jQUery, just pure JS.
This depends on a lot of factors, but in most cases, you will want to load all of your code/html/css in one sitting. It takes fewer requests, and thus boast a higher perceived performance benefit. Unless your code file is over several Megabytes big, loading it when a user requests it is unnecessary.
In addition to all of this, modifying innerHTML and running scripts via eval can be very cumbersome and risky (respectively). Many online references will back this point. Don't assume that, just because a library is doing something like this, it is safe to perform.
That said, it is entirely possible to load external js files and execute them. One way is to stick all of the code into a newly created script tag. You can also just try running the code in an eval function call (though it isn't recommended).
address = "testscript.js";
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(req == null) {
console.log("Error: XMLHttpRequest failed to initiate.");
}
req.onload = function() {
try {
eval(req.responseText);
} catch(e) {
console.log("There was an error in the script file.");
}
}
try {
req.open("GET", address, true);
req.send(null);
} catch(e) {
console.log("Error retrieving data httpReq. Some browsers only accept cross-domain request with HTTP.");
}
I know what GET and POST methods are in ajax, but i was wondering how to implement them into a simple code so i can understand it better, and here's a simple code i found:
<html>
<head>
<title>XMLHttpRequest in Mozilla</title>
<script type="text/javascript">
function Start()
{
try
{
xmlhttp = new XMLHttpRequest();
document.getElementById("Content").innerHTML="<h1>Using XMLHttpRequest Object</h1>";
}
catch (e)
{
document.getElementById("Content").innerHTML="<h1>XMLHttp cannot be created!</h1>";
}
}
</script>
</head>
<body>
Start
<div id="Content"></div>
</body>
</html>
The only thing you're achieving there is to determine whether your browser supports XMLHttpRequest or not (no in explorer, yes on anything else). You are not actually calling the server.
This is a nice link to start learning ajax and javascript in general:
http://www.hunlock.com/blogs/AJAX_for_n00bs
Be sure you check all the site, not only that post.
function ajaxRequest() {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest) { // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null) { // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
var url='http://somedomain.com/getdata.php?doc=sometext.txt'; // This is the URL we will call.
AJAX.open("GET", url, true); // Open the url this object was set-up with.
AJAX.send(null); // Send the request.
AJAX.onreadystatechange = function() { // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete") { // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
}
// End Ajax readystate check.
} // End Event Handler.
}
A good place to get started : https://developer.mozilla.org/en/AJAX/
Your snippet of code will only work in non IE browsers. Don't leave MS out of the party! Use this code
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
Now you can use this object to carry out a request or two.
There's a very comprehensive tutorial here : https://developer.mozilla.org/en/AJAX/Getting_Started
That tutorial will explain it much better than I ever can.
I would like to suggest something that will make your life a whole lot easier. Use jQuery! It makes ajax calls (and anything javascript) much easier. You can do complex operations with very little code.
http://api.jquery.com/jQuery.ajax/
This is for your refrence.
If you are really into Javascript and want to learn AJAX in simple way, I would suggest you the http://w3schools.com/ajax/ajax_intro.asp which is pretty basic and easy to understand. You can even try out there what you have learnt so far.
Also, Jquery is pretty simple as far as Ajax is considered. It basically frees you from all the mess of checking for the browser compatibilities and other stuff. I suggest you take a look at what Elad has mentioned in the above. "Write Less Do more" is the tag for Jquery. Just give it a try.