I usually structure my scripts in javascript like this or something similar when the script depends on some ajax or a server response in general. I really don't feel it's the most efficient way to do things, so what would be a better way to do these types of scripts?
function someclass() {
//some internal variables here
this.var1 = null;
this.var2 = null;
...
//some ajax function which gets some critical information for the other functions
this.getAJAX = function() {
self = this;
urls = "someurlhere";
//jquery ajax function
$.ajax({
type: "GET",
url: url,
dataType: 'json',
complete: function (xhr, textStatus) {
//get the response from the server
data = JSON.parse(xhr.responseText);
//call the function which will process the information
self.processAJAX(data);
}
})
this.processAJAX = function(data) {
//set some of the internal variables here
//according to the response from the server
//now that the internal variables are set,
//I can call some other functions which will
//use the data somehow
this.doSomething();
}
this.doSomething = function() {
//do something here
}
}
So I would use the script something like this:
//instantiate the class
foo = new someClass();
//get the information from the server
//and the processAjax function will eventually
//call the doSomething function
foo.getAjax();
So I really don't like this because it's not clear in the use of the script what is happening. I would like to be able to do something like this:
//instantiate the class
foo = new someClass();
//get info from the server
//in this example, the processAJAX function will not call the doSomething
foo.getAjax();
//do something
foo.doSomething();
This however does not work because usually the response from the server takes some time so when the doSomething is called, the necessary information is not there yet, therefore, the function does not do what it is suppose to do.
How to make this work?
I am sure the answer is already somewhere on StackOverflow, however I could not find anything, so I would appreciate both, either an answer or a link to a resource which would explain this, possible on StackOverflow. Any help is appreciated. Thank you.