my code is simple.
function useXMLHttpRequest() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "test.ashx", false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.onReadyStateChange = function () {
alert("ss");
};
xmlhttp.send("i=5");
alert(xmlhttp.responseText);
}
when I call useXMLHttpRequest.Yes ,it alerts the xmlhttp.responseText's value. but it doesn't alert("ss"). Both in IE9 and firefox.
Anyone can tell me what's worng?
JavaScript (and all other languages that I know of) are case-sensitive, so onreadystatechange is not the same as onReadyStateChange.
Try this instead:
xmlhttp.onreadystatechange = function() {
alert("ss");
};
You have
xmlhttp.open("POST", "test.ashx", false);
3rd parameter is false, which means that you are using synchronous request. For such requests onreadystatechange does not work and is discouraged to use it. Anyway, your request will not go further until complete completion, so alert(xmlhttp.responseText); immediately after xmlhttp.send("i=5"); works correctly and there is no need to handle request state change event.
See more here and here.
Related
Trying to use a pure JS approach to check if I have a valid JS image url. I am getting a warning that XMLHttpRequest is deprecated. What is a better way to do this?
urlExists(url) {
const http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status !== 404) {
return true;
}
return false;
}
You're probably getting a message that the synchronous use of XMLHttpRequest is deprecated (because of its harmful effect on the user experience; it freezes the page while waiting for a response). I can assure you that proper asynchronous use of that API is not deprecated whatsoever.
Here's some example code for the correct use:
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log(this.status) // do something; the request has completed
}
}
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing
xhr.send()
The cause of the warning was that in http.open('HEAD', url, false); you put a third argument (async) as false. As per the https://xhr.spec.whatwg.org/#synchronous-flag it should be set to true.
The warning is probably because you are tyring to do a synchronous request.
I'm a beginner in Javascript , and I want to understand what the method XMLHttpRequest does.
This is the code that I was reading, and I was wondering if someone could explain what it is doing:
var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
Hi I am not really good in explanations, but I will try to explain this in details as I see and understand this.
The XMLHttpRequest is an object. It is used for exchanging of data with a server. So with its use you can send some data to the script on the server(request) and get some data back from it(response). That response data can be displayed instantly on the page without page reloading. So this process call AJAX.
I would read your provided code as
//define a variable
var xhttp;
/*assign a XMLHttpRequest object to this variable
check if the global object window has a XMLHttpRequest object already
if not and user have a newer browser, create one (new XMLHttpRequest - for IE7+, Firefox, Chrome, Opera, Safari browsers) or user have an older browser (ActiveXObject("Microsoft.XMLHTTP") - for IE6, IE5 browsers)
xhttp.open method specifies the type of request(method GET, Script on server, asynchronous)
xhttp.send method sends the request to a server*/
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
But you have to check the readyState property of the XMLHttpRequest object as well
xmlhttp.onreadystatechange = function() {
//4: request finished and response is ready
//200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//it is available in this property - xmlhttp.responseText
}
}
The whole peace of code should look like:
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//jquery example
$('div').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "script.php", true);
xmlhttp.send();
Hopefully this helped, good luck!
It's a reference to an AJAX request.
See more at the MDN site.
In a nutshell, it is sending a GET request to script.php.
An XMLHttpRequest is a JavaScript object made for making AJAX request. I am not fully sure that code is correct. Usually you make an instance of the XMLHttpRequest object. Then you check the window ready state to make the request. Finally you make the request. This is an example of that:
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
I hope that helps!
Happy coding!
I'm playing around with this XmlHttpRequest thing. In some tutorials and books, it is the onload function the one that is called when the request is done. In my little experiment, this function is never called. Here's my code:
window.onload = function() {
var url = "http://www.google.com";
var request = new XMLHttpRequest();
request.onload = function() {
var state = this.readyState;
var responseCode = request.status;
console.log("request.onload called. readyState: " + state + "; status: " + responseCode);
if (state == this.DONE && responseCode == 200) {
var responseData = this.responseText;
alert("Success: " + responseData.length + " chars received.");
}
};
request.error = function(e) {
console.log("request.error called. Error: " + e);
};
request.onreadystatechange = function(){
console.log("request.onreadystatechange called. readyState: " + this.readyState);
};
request.open("GET", url);
request.send(null);
};
I'm testing this on the last Firefox release (just updated today). The log line in onload is never printed, and the breakpoint I set in the first line is never hit. However, the onreadystatechange function is called twice, and the http request is actually made. This is what firebug's console shows:
request.onreadystatechange called. readyState: 1
GET http://www.google.com/ 302 Found 174ms
request.onreadystatechange called. readyState: 4
NS_ERROR_FAILURE: Failure
request.send(null);
There's an error in the send line. I've tried changing it to request.send() with identical result.
At first I thought this might be the browser trying to prevent XSS, so I moved my html driver page to a Tomcat instance in my dev machine, but the result is the same.
Is this function guaranteed to be called? As I've said above, it's common to be seen in most tutorials, but on the other hand in the W3C spec page, the hello world snippet uses onreadystatechange instead:
function processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null &&
this.responseXML.getElementById('test').textContent) {
// success!
processData(this.responseXML.getElementById('test').textContent);
return;
}
// something went wrong
processData(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
It checks readyState == this.DONE. DONE has the value 4, which is what I can see in my log. So if this were a XSS related issue, and the browser were preventing me to make the connection to a different domain, then why the actual connection is made and the DONE status is received???
PS: Yes, I know there are powerful libraries to do this easily, but I'm still a JavaScript noob so I'd like to understand the low level first.
UPDATE:
I've changed the URL to one inside my domain (localhost), and the error is gone but the onload function is still not being called. Tested in IE8 and does not work. Tested in Chrome and works. How's that?
UPDATE 2:
Tested again in Firefox, and now it works. Probably the old page was still cached so that's why I couldn't notice it immediatly. Still failing in IE8, I'll try to test it in a newer version.
It looks like it was indeed a XSS issue and Firefox was blocking the onload call. I can't still understand why the http network request was actually being done and the onreadystatechange was being called with the DONE readyState.
I changed the URL to another one in the same domain, and now it works in Firefox (after some cache-related false attempts) and in Chrome. It still does not work in IE8, despite the official docs say it is supported. I've found this SO answer which states otherwise. It looks like the onload function is a more modern convenience method and the old way of checking the result is using onreadystatechange instead.
I guess I'll accept this answer as the solution unless a more detailed answer is provided.
The onload handler won't be called for yet another reason, I'm adding it here just so it can be helpful to someone else referencing this page.
If the HTTP response is malformed, the onload handler will not be called either. For example, a plaintext response of 10 bytes that advertises a length of 14 in Content-Length header will not invoke the onload handler. I wasted hours on client code before I start to replace back-end units with test stubs.
IE has different method to create xmlhttprequest.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
};
same this article:https://www.html5rocks.com/en/tutorials/cors/
I have checked everywhere on all other questions to do with this and I can still not find an answer that works so I am posting this here.
Here is my code:
var link;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
link = xhr.responseText.split("::::")[0];
alert(link);
}
}
}
var url = "http://youtube.thegoblin.net/banner/getImage.php?name=" + actualName;
xhr.open("GET", url, true);
xhr.send();
Now, this works absolutely fine in Chrome, but not in Firefox. I know that the problem is not to do with onreadystatechange not being used with synchronous HTTPRequests because this is asynchronous, and it works fine in Chrome. I have tried it as a synchronous request, but anything after xhr.send(); does not run and I do not know why.
Why does this work in Chrome and not Firefox? And how can I get this to work in Firefox,
thanks.
Update
I believe the problem is becasue the request is cross domain. How can I get past this?
I'm new in JS, and having quite hard time reading the following JS code.
The first parameter of the function is a url to a PHP script, the second is a string.
What confuses me is how to read code after the line:
self.xmlHttpReq.open('POST', strURL, true);
What happens after this? Which code should i look after this line? The script?
What happens after open?
function check_detail(strURL, pids)
{
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function()
{
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids);
}
self.xmlHttpReq.send(getquery(pids));
}
The key is the call to "send()", which actually launches the HTTP request. That happens, but the code then proceeds immediately without waiting for the result.
When the server responds, the browser will invoke the anonymous function set up as the "readystatechange" handler. Exactly when that happens is unpredictable; it's asynchronous, in other words.
Thus, the "updatepage()" call will happen long after the "check_detail()" function has returned.
When you make an Ajax request (which is what you are doing here) it is asynchronous, which means that you don't know exactly when it will return so you can't just wait for the return.
Instead, you set up your function so that, when the request returns, a function is kicked off to handle the response. This is the onreadystatechange piece.
So the chronology will be: first the send() will occur, which will send the result of the getquery() method up to the PHP page. When that returns, the function defined within onreadystatechange will fire, which will call updatepage() and pass it both the text that was sent back from the Ajax call, and also the pids parameter.
If you're new to JavaScript, then I'd say it's a waste of time trying to figure out what's going on here - you're learning how to use the XHR object, how to make that cross-browser, and you're learning JavaScript at the same time.
I'd recommend doing the Ajax with a JavaScript library such as jQuery - don't try to learn it all now while you're learning JavaScript as well.
Most of that could be replaced with something along the lines of:
$.post(strURL, function (data) {
updatePage(data);
});
this is simple Ajax function
function check_detail(strURL, pids)
{
// definning new variable
var xmlHttpReq = false;
// creating variable self which will function as this
var self = this;
// creating HTTP request maker for Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// creating HTTP request maker in IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
// so this is the confusing part right ?
// xmlHttpReq.open opens connection tu the strURL and infomation sending method
// will be POST method ( other passible values can be GET method or even else )
self.xmlHttpReq.open('POST', strURL, true);
// this defines HTTP request header (small information about what we are sending)
// in fact this is sending Content-type of information
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// when HTTP request maker state will be changed for example:
// the data will be sent or data will be received this function will be fired
self.xmlHttpReq.onreadystatechange = function()
{
// readyState 4 means data has been received
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids); // updatepage is user defined function
}
// this actually sends the HTTP request which is made above
// but don't be confused because of this code ordering
// I mean the function defining what to do when content will be received is implemented
// before sending HTTP request right ?
// thats because if the data is too small and internet is really fast HTTP query can be
// executed faster then defining new function which will cause javascript error
self.xmlHttpReq.send(getquery(pids));
}
hope this helps
if not
more about ajax: http://en.wikipedia.org/wiki/Ajax_(programming)