AJAX request doesn't go to readystate 4 - javascript

I'm trying to use AJAX for the first time and I've encountered an issue. I didn't manage to resolve it by reading tutorials.
I have a PHP file on my server which echoes the correct output when I access the file directly. However when I try accessing it through a HTML. Here is my javascript code:
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open('GET', 'http://www.mysite.com/myfile.php?variable1=' + variable1 + "&variable2=" + variable2, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
var receivedString = httpRequest.responseText;
console.log(receivedString);
} else {
console.log(httpRequest.readyState);
}
};
nothing happens; neither receivedString nor the value of httpRequest.readyState is output. What could be the reason?

Append httpRequest.send(null); to your code.
The request is not sent to the server until the send method is called, so the readyState property does not change and the onreadystatechange event is not fired.

Related

Why the "Uncaught ReferenceError:" when making my HTTP request?

"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "OMMITTED FOR PRIVACY REASONS"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();
See link below for a screenshot of the errors, but here's what I'm getting:
An Uncaught ReferenceError on line 12 where my onreadystatechange is.
I also get an error saying 'responseMethod' isn't defined at
makeRequest nor when I call it.
Also getting an error on the very last line for some reason.
Your code looks good. I just replaced your code with my api key and everything worked (see below).
Can you be more specific about the browser where you get an error?
I tried in the latest chrome and firefox and there is no problem.
"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "4ff5002c91520701ec111b6082de9387"; // This key might expire soon.
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();

How to catch empty response error in JavaScript without JQuery?

I'm developing chat app using the long polling technique for real time updates, but after a few minutes of "polling" a request I get the following error:
net::ERR_EMPTY_RESPONSE
As I read , this is expected if the requests waits too long then after a while it responses an empty response , Now I would like to be noticed when such a thing happens ,so I can resend another request to the server.
here is my code :
client.js:
function httpMsgRequest(counter,callback){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://localhost:8080/messages?counter=" + counter);
httpRequest.send();
}
function msgPoll() {
try{
httpMsgRequest(counter,function(res){
//callback body
msgPoll();
});
}catch{
msgPoll();
}
}
msgPoll();
I tried to add the try-catch like above but it did not solve the problem. Any one has some idea and can help? Thanks in advance.

How do I manage multiple, overlapping XMLHttpRequests?

I'm working on my first AJAX project, and I've started by setting up the following functions:
function sendHTTPRequest(callback,filename,data) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = callback;
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, parse the XML data
} else {
// error
}
} else {
// not ready
}
}
This has worked well but I've now gotten to the point where I have more than one simultaneous HTTP request, and my single global httpRequest variable isn't cutting it. It seems to me I could use an array, and .push a new XMLHttpRequest onto the stack each time sendHTTPRequest() is called, but how can I tell my various callback functions which item in the stack to parse? Or is the a better way to handle this process? (I'm using these to handle requests to different pages, with results that need to be parsed differently.)
Thanks!
Use a local variable and a per-request callback, which in turn calls the given callback. The changes required are surprisingly small; see ** lines:
function sendHTTPRequest(callback,filename,data) {
var httpRequest; // ** Local variable
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// ** Callback specific to *this* request
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, call the callback
callback(httpRequest);
} else {
// error, call the callback -- here we use null to indicate the error
callback(null);
}
} else {
// not ready
}
};
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback(xhr) {
if (xhr) {
// successful, parse the XML data, for instance
var x = xhr.responseXML;
} else {
// not ready
}
}
You could have it give the callback more information (for instance, the filename and data arguments).
If you use promises, you could have sendHTTPRequest return a promise instead of accepting a direct callback.
httpRequest = new XMLHttpRequest();
Don't use a global. Use a local variable.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
Don't use a global. Event handlers are called in the context of the object on which they fire. Use this.

XMLHttpRequest in IE-7

I'm creating XMLHttpRequest as follows:
function checkDependencyFormFilledStatus(appName,formName){
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","checkFormDependency.action formName="+formName+"&applicationName="+appName,false);
xmlhttp.send();
var dependentFormEmptyStatus = Ext.JSON.decode(xmlhttp.responseText);
alert(xmlhttp.responseText);
return dependentFormEmptyStatus;
}
The response returned by the object is dependent on the database which the action class is using.
This works fine in Firefox 10.0.
But for IE7, it returns correct response only for the first time. And for the rest of the function calls, it returns the same response (no matter what changes we make in the database). It updates its response only when I close the tab and open it (not even on reloading the page).
How to make it work in IE 7?
Sounds like the response is being cached.
Add a psuedo-random string (e.g. a timestamp) to the end of the URI to cache burst.
you are simply having a caching issue with IE7, as it caches the XMLHttpRequest() after it created it and store it in its memory. even with subsequents xmlhttp=new XMLHttpRequest(); the variable don't get any assigment because it already has an instance (from your first xmlhttp=new XMLHttpRequest(); ) .
what you need to do is to invalidate and destroy your XMLHttpRequest request after every use.
you first create your XMLHttpRequest (for msie 7) like this:
function createXMLHttpRequest(){
var xmlHttp = null;
if(typeof XMLHttpRequest != "undefined"){
xmlHttp = new XMLHttpRequest();
}
else if(typeof window.ActiveXObject != "undefined"){
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.4.0");
}
catch(e){
try {
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = null;
}
}
}
}
return xmlHttp;
}
so to create it each time in the function you want to use.
function checkDependencyFormFilledStatus(appName,formName){
if(xmlHttp_global){
xmlHttp_global.abort(); // abort the current request if there's one
}
// Create the object each time a call is about to be made
xmlHttp_global = createXMLHttpRequest();
if(xmlHttp_global){
xmlHttp_global.onreadystatechange = myCallbackFunction; // make you callback thing here
xmlHttp_global.open("GET","checkFormDependency.action formName="+formName+"&applicationName="+appName,false);
xmlHttp_global.send(null);
}
}
in your callback ("onreadystatechange" function) you delete it after using it
function myCallbackFunction()
{
if(xmlHttp_global && xmlHttp_global.readyState == 4){
//do your thing here and ... or nothing
var dependentFormEmptyStatus = Ext.JSON.decode(xmlhttp.responseText);
alert(xmlhttp.responseText); // like this for example?
xmlHttp_global = null; //delete your XMLHTTPRequest
}
}
so IE 7 will find each time an empty reference and will have the need to recreate it again for each use.
if you don't want to create and delete it eacht time you simply play with some HTTP-Headers in your XMLHTTPRequest
xmlHttp_global.setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT");
xmlHttp_global.setRequestHeader("Cache-Control", "no-cache");
like suggested here
Another alternatives include:
Using POST method over GET method
xmlHttp_global.open("POST","checkFormDependency.action",false);
xmlHttp_global.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // or another content type , its up to you
xmlHttp_global.send("formName="+formName+"&applicationName="+appName);
Using a "dummy" variable in your query-String to burst out the cacher of IE(7,6)
xmlHttp_global.open("GET","checkFormDependency.action formName="+formName+"&applicationName="+appName+"randomVar="+Math.Random(),false);
Links
XMLHTTPRequest cache in IE 7 and 6

Ajax readyState always 1

I'm tying to do what seems like a simple ajax but can't get it to work. Here's my code:
var xmlHttpRequest;
function processRequest(){
alert("process request called with " + xmlHttpRequest);
if(xmlHttpRequest.readyState==4){
alert("status = " + xmlHttpRequest.status);
if(xmlHttpRequest.status == 200){
}
} else {
alert("process request no luck readyState = " + xmlHttpRequest.readyState);
}
alert("process request exiting");
}
function updateCount(customerID, productID) {
xmlHttpRequest = init();
function init(){
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support AJAX!");
}
}
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.onreadystatechange = processRequest();
}
Like I said in the subject line, readyState is always 1. What am I doing wrong?
Thanks!
Eddy
You are calling processRequest before you start your request.
xmlHttpRequest.onreadystatechange = processRequest();
is wrong and has to be
xmlHttpRequest.onreadystatechange = processRequest;
This will store a reference to your method instead of calling it directly.
As soon as the ready state changes, the xmlHttpRequest object trys to call this reference.
Add xmlHttpRequest.send(); after xmlHttpRequest.onreadystatechange = processRequest;.

Categories

Resources