AJAX issue returning the value - javascript

I am using a javascript function that calls another javascript function (zConvertEmplidtoRowid) that uses an ajax call that runs a query to return data in a variable (rowid). My problem is I don't know how to return the data to the original function.
Here is a snippet of the original function calling the ajax function (zConvertEmplidtoRowid)
var rowid = zConvertEmplidtoRowid(emplid);
//the alert should show what the query via ajax returned
alert(rowid);
zEmployeePortrait(emplid, ajaxlink);
}
And here is the ajax function...I imagine somewhere in here I need to place the return, but I've never used ajax before, so I'm not sure.
function zConvertEmplidtoRowid(emplid, ajaxlink, callback) {
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var rowid = request.responseText;
callback(rowid);
}
}
var ajax_link = ajax_link + "?emplid=" + emplid;
request.open('GET', ajax_link);
request.send();
}

As #epascarello pointed out, the ajax call is asynchronous and the code you have written is expecting the call to return in a synchronous way.
You have two options:
1) Make the ajax call synchronous (I highly recommend not to take this route).
2) Pass a callback function as a parameter to the function making the ajax call and then invoke the callback function once the call returns.
e.g:
function zConvertEmplidtoRowid(emplid, ajaxlink, callback) { //Added a callback function parameter
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var rowid = request.responseText;
//now you invoke the callback passing the rowid as argument
callback(rowid);
}
}
var ajax_link = ajax_link + "?emplid=" + emplid;
request.open('GET', ajax_link);
request.send();
}
zConvertEmplidtoRowid(emplid, ajaxlink, function(rowId) {
alert(rowId);
zEmployeePortrait(emplid, ajaxlink);
});

As epascarello has implied in his comment, you need to make the javascript call synchronously in order to get a return value...
I tend to use jquery to assist with the call, but a quick google suggests you can do it your way by changing:
request.open('GET', ajax_link);
to:
request.open('GET', ajax_link, false);
and the response is then accessible through:
request.responseText
taken from here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Related

How to separate XMLHttpRequest from the main function for better visbility/testibility (without Promises / asnyc/await )

Imagine this function:
function myMainFunction() {
doSomeInitialStuff();
// more stuff..
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
// Now that we know we received the result, we can do the heavy lifting here
if (xhr.status == 200) {
console.log("ready 200");
let result = JSON.parse(xhr.responseText);
doStuff(result);
// and much more stuff..
} else {
console.log("error", xhr.status);
return undefined;
}
}
};
xhr.open("GET", "http://example.com", true);
xhr.send(null);
}
This works fine, but it is impossible to test, and this function has become a monster.
So I'd like to refactor it, by separating all the different parts in their own unique functions.
The problem is, I do not know how to extract the XHR part and still keep it working.
I cannot use Promises nor asnyc/await and have to stick to using plain XHR.
What I'd normally do is to create a seperate async function for the ajax call (or the xhr in this case). Simply await it's result and go from there. Easy to separate. But I do not have the luxury of await or anything this time.
What I am trying to get at is something like this
function refactoredMyMainFunction() {
doSomeInitialStuff();
// more stuff..
let result = xhrFunction();
doStuff(result); // result would be undefined here, since I cannot wait for the xhr request to finish.
}
You can implement a callback-based API:
function myMainFunction() {
doSomeInitialStuff();
// more stuff..
xhrFunction(doStuff);
}
function xhrFunction(cb) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
// Now that we know we received the result, we can do the heavy lifting here
if (xhr.status == 200) {
console.log("ready 200");
let result = JSON.parse(xhr.responseText);
cb(result);
// and much more stuff..
} else {
console.log("error", xhr.status);
return undefined;
}
}
};
xhr.open("GET", "http://example.com", true);
xhr.send(null);
}

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.

Empty return value when parsing JSON using XMLHttpRequest

I have been trying to parse a bit of JSON from an API now and it was all working when I used
xmlHttp.open('GET', url, false);
But when I later wanted to expand my code using timeouts for the requests my function started to return empty values.
This is the function doing the actual parsing:
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
obj = JSON.parse(xmlHttp.responseText);
console.log(obj);
}
}
};
When I log the object returned here using console.log I get the JSON printed out to the console normally but later in my function I am returning the obj variable but it is always empty.
Here is the whole function:
static Parse(url: string): Object{
Asserts.isUrl(url, 'URL is invalid');
var obj = new Object();
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
obj = JSON.parse(xmlHttp.responseText);
//console.log(obj);
}
}
};
xmlHttp.open('GET', url, true);
xmlHttp.timeout = 2000;
xmlHttp.ontimeout = function () {
xmlHttp.abort();
throw new Error("Request Timed Out.");
};
xmlHttp.send();
return obj;
}
My first thought that it had something to do with the scope in Javascript but now after being stuck here for a few hours without progress I am clueless.
As I mentioned inside the xmlHttp.onreadystatechange = function () the console.log is actually logging the correct value. It's just that the obj variable created at the start of the function is not getting the value.
AJAX is asynchronous. This means that the onreadystatechange function will be called at a much later stage, probably after you have already returned from the Parse method. So you should not be trying to return obj from the Parse method. You would rather have the Parse method take an additional parameter that represents a callback function which you will invoke inside the onreadystatechange event and pass it the resulting object.
Here's what I mean:
static Parse(url: string, done: (obj: any) => void): void {
Asserts.isUrl(url, 'URL is invalid');
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var obj = JSON.parse(xmlHttp.responseText);
// Pass the resulting object to the callback function
done(obj);
}
}
};
xmlHttp.open('GET', url, true);
xmlHttp.timeout = 2000;
xmlHttp.ontimeout = function () {
xmlHttp.abort();
throw new Error("Request Timed Out.");
};
xmlHttp.send();
}
and here's how you would call the Parse function:
Parse('http://foobar', function(obj) => {
// TODO: do something with obj here
console.log(obj);
});
So basically when you are writing a javascript application that uses asynchronous AJAX calls you should stop thinking in terms of sequential functions that you will invoke one after the other and which will return values. You should start thinking in terms of callbacks.
You need to pass a callback to the function:
static Parse(url: string, onSuccess: Function): Object{
Asserts.isUrl(url, 'URL is invalid');
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var obj = new Object();
obj = JSON.parse(xmlHttp.responseText);
onSuccess(obj)
}
}
};
xmlHttp.open('GET', url, true);
xmlHttp.timeout = 2000;
xmlHttp.ontimeout = function () {
xmlHttp.abort();
throw new Error("Request Timed Out.");
};
xmlHttp.send();
}
and call the function with your callback parameter.

Getting undefined in javascript when calling ajax

function get_request(url) {
var request = new getXMLObject();
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert(request.responseText);
var data = eval('(' + request.responseText + ')');
alert(data);
return data;
}
}
request.open("GET", url, true);
//alert(document.getElementById('energy').innerHTML);
request.send();
}
function loadjobs() {
var url = "loadjobs.php?tab=1&id=1111";
//var data=
//alert(check());
alert(get_request(url));
//alert(data);
}
When i m getting data in json format...i am gettin NULL in alert(get_request(url));
while i m getting in alert(data);
Help me
This is because the request in asynchronous . The get_request(url) function does to return anything and hence the null ( although I think it should be undefined and not null ) .
The onreadystatechange function gets called later in the time , when the AJAX request has been completed and the data is returned from the server and hence the alert there works .
This is a misunderstanding of how AJAX works. Ajax is asynchronous. The onreadystatechange function will be called after loadjobs(). The "return path" you are specifying can never work. get_request() will never be able to return the fetched value.
You have two options. Either make the script synchronous - this can be done but is not recommended because it can freeze the browser.
Or, better, handle everything you need to do inside the onreadystatechange callback.
Well, it's an asynchronous call. You will receive the data of request your after get_request has already returned. That means your request.onreadystatechange = function () will be executed long after alert(get_request(url)); is already finished. This means get_request will not be able to return any data from the AJAX call. That's what you have the request.onreadystatechange callback function for, to execute code at an undefined later time when you received the response.
The problem is that Ajax requests work asynchronously. So you can't return the data right away. The way you should do it is to specify a callback function which will handle the response data.
function handleJSON( data ) {
// ...
// do whatever you want to do with the data
}
ajax( "url/file.php?param=value", handleJSON );
////////////////////////////////////////////////////////////////////////////////
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
// onError
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
// onSuccess
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

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