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

"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);
}
}
})();

Related

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.

Waiting for get request response from JS does not work

In my javascript code I have:
function getThing(){
var url = "myhost/thing";
var x = new XMLHttpRequest();
x.open("GET", url, false);
x.onload = function (){
return x.responseText
}
x.send(null);
}
console.log(getThing())
And console log gives me undefined.
What am I doing wrong?
Your HTTP request is executed asynchronously, and getThing is not returning anything other than undefined. Instead, your onload handler is returning the requested value, which is not used.
Instead, you need to wait with logging until the call has returned:
function getThing(){
var url = "myhost/thing";
var x = new XMLHttpRequest();
x.open("GET", url);
x.onload = function (){
console.log(x.responseText);
}
x.send(null);
}
getThing();

AJAX request doesn't go to readystate 4

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.

JavaScript function to return AJAX response (no jQuery)?

I need a pure JavaScript function (Sorry, no jQuery) that will return the response from a successful AJAX call. Here's the function I've got so far, I want to return the HTMLobject with the HTML from the response:
function getHtml(url) {
var httpRequest;
var HTMLobject;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!httpRequest) {
console.error('Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
// OK, turn the string into HTML.
var div = document.createElement('div');
div.innerHTML = httpRequest.responseText;
// Assign the converted HTML to HTMLobject.
HTMLobject = div.childNodes[0];
} else {
console.debug('There was a problem with the request.');
}
}
};
httpRequest.open('GET', url);
httpRequest.send();
return HTMLobject;
}
I know why, HTMLobject returns undefined, but I need it to work. Is there a way to have the function return the object after the AJAX has completed?
No, the solution is such a case is to use a callback function.
Ex:
function getHtml(url, callback) {
....
....
callback(HTMLobject); //instead of returning the HTMLobject, call a callback function as pass the `HTMLobject` as a argument.
}
Usage:
getHtml('url', function(HTMLobject){
//Do something with HTMLobject
});
instead of
var HTMLobject = getHtml('url');
//Do something with HTMLobject
Making a request async: false is a bad idea since it will block the page till the request is completed(UI will not get redrawn and ui interaction will not happen).
make request synchronous , just by doing as below
httpRequest.open('GET', url,false);//false make request synchronous
httpRequest.send();
The "false" option says the call is synchronous, meaning that the code will hang until a response comes back

Ajax request not passed to controller

I send an AJAX request to my controller. This development done in JSP and Spring environment. SimpleFormController is overridden by the controller I'm using.
Using JavaScript I create the object and send the request. this request is not getting passed to controller.
JavaScript code which send the request.
function getStates(){
var httpRequest;
var country = document.getElementById('countryName');
alert(country);
var url = '/developer/register.htm';
url = url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true');
if (window.ActiveXObject)
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
httpRequest = new XMLHttpRequest();
}
httpRequest.open("GET", url, true);
httpRequest.onreadystatechange = function() {processRequest(); };
httpRequest.send(null);
}
function processRequest() {
if(httpRequest.readyState == 4){
alert("inside ready state");
var response = http.responseText;
document.getElementById('states').innerHTML = response;
}
}
Variable url is given in the way how I have mentioned in dispatcher servlet.
The browser shows an error in processRequest() function telling that httpRequest is not defined. but, I don't get this error in the previous lines. I use this object in getStates() function.
It is because variable httpRequest should be defined outside getStates() function. Otherwise processRequest() cannot see it.
Either declare httpRequest outside getStates() (as a global variable) or pass it to processRequest():
httpRequest.onreadystatechange = function() { processRequest(httpRequest); };
function processRequest(httpRequest) {

Categories

Resources