How to make an efficient ajax based javascript script - javascript

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.

The standard pattern for this is to accept a callback function to your asynchronous method, which the class takes responsibility for calling when the operation is complete.
function someclass() {
this.getAJAX = function(callback) {
this.afterAJAXCallback = callback;
...
});
this.processAJAX = function(data) {
...
if (this.afterAJAXCallback) this.afterAJAXCallback();
}
}
Then you can use a closure callback in place to structure your code, much in the way you would when using jQuery's $.ajax:
foo = new someClass();
foo.getAjax(function() {
foo.doSomething();
});

Sounds like you want an ajax event listener or a callback. Do some searches for that and you'll find some solutions. A lot of them will be jQuery-based, but it is certainly possible to do it without jQuery if that is a bad fit for your application.
For jQuery, the relevant documentation is at http://api.jquery.com/jQuery.ajax/. It doesn't call it an event listener, but see the part about context and the callback for succes.
Another possibility would be to do your ajax calls synchronously rather than asynchronously. (Again, do some searches and you'll find lots of stuff.) If you go that route, you want to be careful about making sure that the synchronous call doesn't basically hang your app waiting for a response.

If you use XMLHttpRequest() synchronous you can do it the way you prefer.

Related

Mixing sync and async javascript/jquery and getting a success function at the end

Wondering what the best solution to this problem is, also this is not my actual code structure or names but the simplest way to illustrate the problem.
I have a function which was purely used to perform an ajax call and load a template with jquery.
function load(template) {
$('#container').load(template, data, function() {
// complete code here
});
}
Focusing on the 3rd param in $.load(), namely a callback function that runs when the request is complete.
Now I have my load() function in another wrapper function:
function processTask(variable) {
load(variable);
}
The problem I have is I need some code to run after the ajax load is complete, however as my app has grown my wrapper function processTask may or may not invoke an ajax load so I can't perform my must needed code inside the complete callback.
Do I change my $.load() to perform synchronous or just manage my code better so that if I am calling a $.load() it puts my needed code in the callback and if not it places it where I need it to be?
I have read about javascript Promises and I'm unsure if they will help in this situation.
EDIT
So my processTask is an object method.
function classObj(name, fn) {
this.name = name;
this.processTask = fn;
this.load = function(template) {
$('#container').load(template, data, function() {
// complete code here
});
}
}
And in context I do this:
var task = new classObj('taskName', function() {
this.load('myFile.php');
// Or another function and not load() based on whats needed in the task.
});
Basically I have an object that I can add custom methods to at will and they can easily be called dynamically, until now they have always loaded a file.
First, change your load function to return the xhr from get (or ajax):
function load(template) {
return $.get('myFile.php', data, function(result) {
$('#container').html(result);
});
}
Then, within your code you can use when then to perform your code after the load completes if applicable:
var xhr;
/* ... */
if(something){
xhr = load(template);
}
/* ... */
if(xhr){
$.when(xhr).then(doSomething);
} else {
doSomething();
}
And in fact, this can be simplified using the fact that a non-deferred object passed to when (including undefined apparently) will execute the then immediately and get rid of the if:
$.when(xhr).then(doSomething);
If xhr is undefined then when will resolve immediately causing then to execute immediately.

Elegant solution to conditional AJAX call

I am writing some javascript that includes a series AJAX calls and I am looking for an elegant solution to the following issue: The goal of the script is to gather parameters and then execute an API call with these parameters. The very first time the call is executed there is one parameter that needs to be requested from the server - every subsequent call will use a stored value of this parameter. This is where the issue begins. I want a conditional AJAX call to be made only if this is the first time. I don't want to put the rest of the code into the success function of that AJAX call as that seems convoluted. I would like something like the following but due to the obvious asynchronous nature of the call I realize this is not possible. I also want to avoid having a synchronous call as this would cause the thread to block:
var myParameter;
if(!params.myParam.isStored) {
myParameter = getParamWithAjaxCall();
} else {
myParameter = params.myParam;
}
// Continue with the rest of execution here of which there is a lot of code
Sorry if this seems like an obvious question and I have looked into solutions using the following but I am looking for an experienced opinion on what the most elegant solution would be:
jQuery: when.done
jQuery: async: false
Passing a callback to the Ajax call
I would create a wrapper function which you pass your logic to as a callback in done(). Something like this:
function makeRequest(callback) {
if (!params.myParam) {
// retrieve param
$.ajax({
url: '/getParam',
success: function(data) {
params.myParam = data.param;
}
}).done(callback);
}
else {
// param already has a value...
callback();
}
}
makeRequest(function() {
// make your AJAX request here, knowing that params.myParam will have a value.
});
You could use promises like so (I have used JQuery promises here):
function ParameterValueProvider() {
var parameterValue;
return function() {
var deferred = $.Deferred();
if ( parameterValue === undefined ) {
$.ajax({
// ... ajax parameters go here
}).done(function(rsp) {
parameterValue = rsp;
deferred.resolve(parameterValue);
});
}
deferred.resolve(parameterValue);
return deferred;
}
}
// Your Application
(function() {
'use strict';
var getParam = ParameterValueProvider();
// this will get the value from server the firs time
// and subsequent calls will use the cached value
getParam().then(function() {
// subsequent ajax calls go here
});
}());

PageMethods slows the process and working descending

I have many pagemethods on my page. Each methods are used for fetching data from the database. I have ordered them in the following way. but my problem is the lines outside the success methods but inside the main function are working before the pagemethods complete the process
function check_valid()
{
// some code
Pagemethod1
function suc1()
{
//some code
PageMethod2
function suc2()
{
//some code
Page Method3
function suc3()
{
//some code
}
function err3(){}
}
function err2(){}
}
function err1(){}
return true; //this line is working before the pagemethods complete the process
}
I'm not familiar with "PageMethods" but it sounds like each of these functions is asynchronous as it is receiving data from a remote database. Because JavaScript operates within one single thread, asynchronous processes usually have an option to attach a callback function that fires once the process is complete. This allows javascript to do other things such as return true while its waiting for your slow database call, explaining your observation.
Instead, use a callback pattern with your database API:
editDatabase(args*, function() {
//Stuff to do database call is complete
});
Alternatively, your database API might use an event pattern:
var myDb = new DB();
myDb.edit(args*)
myDb.bind('complete', function() {
//Stuff to do database call is complete
});
Or, your database API might use promises, which you can read about here.
These patterns may take some getting used to if you are moving from a synchronous language, but they are essential to JavaScript. You can also find a good guide to the asynchronous aspects of JavaScript here.
Change your code as follows
function check_valid()
{
// some code
Pagemethod1
function suc1()
{
//some code
PageMethod2
function suc2()
{
//some code
Page Method3
function suc3()
{
//some code
return true;
}
function err3(){}
}
function err2(){}
}
function err1(){}
}
Because PageMethods will work one by one.
Using a javascript class may help. Also callbacks are key for ajax.
function check_valid(){
var fn = this; //assign this to a variable for ease of use
var callbacks = []; //array to store all results
var calls = []; //all ajax calls
this.complete = function(callback){
function check(){
if(callbacks.length==calls.length){
callback(callbacks);
}else{
setTimeout(function(){
fn.check()
},50);
}
}
return fn;
}
this.callServ(params){
calls.push(params);
params.success = function(ret){
callbacks.push({data:ret,status:'success'});
}
params.error = function(ret){
callbacks.push({data:ret,status:'success'});
}
$.ajax(params);
return fn;
}
return this;
}
This should allow you to do multiple calls systematically and then use a single callback to handle them all. I use jquery ajax to make the ajax call easier, and pass its same parameters.
So it would look like this to use:
var checkValid = new check_valid();
checkValid.callServ({url:url,data:data});
checkValid.callServ({url:url,data:data});
checkValid.callServ({url:url,data:data});
checkValid.complete(function(data){
//data is an array of all call serv returns.
});
This may be far from what you currently have, the amount of information does not tell me enough of what exactly is being done. This example may be a little advanced, but it can give the illusion of being synchronous, at least as close as javascript can get.
I have found my own solution. After a long research i have come to the solution. that is pagemethods will be slow only because of their arrangement. We have to decide where to call it and after which we have to call. Since I have reordered them, it gave some fault. Now its working good.

Setting timer after an asynchronous call returns

I have an asynchronous Ajax function which runs a command string at the server side and returns the result to the client. It calls a callback to process the result.
function ajaxCall(commandStr,callback){
var url=......//make a url with the command string
jquery.get(url,function(result){
//process the result using callback
callback(result);
});
}
The asynchronous call (ajaxCall) may take a while to be finished but I want it to do the same command after an interval (1000ms).
I want to write a function that is like this:
function ajaxCallRepeated(interval,commandStr,callback)
I tried closures like this:
function ajaxCallRepeated(interval,commandStr,callback){
//This feature uses closures in Javascript. Please read this to know why and how: http://jibbering.com/faq/notes/closures/#clSto
function callLater(param1,param2,param3){
return (function(){
ajaxCall(param2,function(out,err){
if(param3)param3(out,err);
var functRef = callLater(param1,param2,param3);
setTimeout(functRef, interval);
});
});
}
//the first call
var functRef = callLater(interval,commandStr,callback);
setTimeout(functRef, interval);
}
Then I call it like this:
ajaxCallRepeated(2000,"ls",function(result){
alert(result);
});
But it only runs the command 2 times.
How can I write a function that will reschedule itself after it is called as a callback of an asynchronous function?
PS. I want to fire another Ajax call after the previous one is finished. Also, it worth to mention that axashCallRepeated() will be called with various parameters, so several Ajax calls are running in parallel, but for each commandStr, there is only one Ajax call going on, and after the Ajax call returns, another one will be fired after X seconds.
I would not use setTimeout to trigger the second Ajax call ! Because you never know how long it will take and if it's finished !
As far as you tagged your question right and you ARE using jquery you should consider something like this:
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
// The AJAX is successfully done, now you trigger your custom event:
$(document).trigger('myAjaxHasCompleted');
},
dataType: dataType
});
$(function(){
//somehwere in your document ready block
$(document).on("myAjaxHasCompleted",function(){
$.ajax({
//execute the second one
});
});
});
So this would ensure that the ajax post is DONE and was successful and now you could execute the second one. I know its not the exact answer to your question but you should consider on using something like this ! Would make it safer I guess :-)
The key to solve this problem is to save a reference to the closure itself and use it when scheduling the next call:
function ajaxCallRepeated(interval,commandStr,callback){
//This feature uses closures in Javascript. Please read this to know why and how: http://jibbering.com/faq/notes/closures/#clSto
function callLater(_interval,_commandString,_callback){
var closure=(function(){
ajaxCall(_commandString,function(out,err){
if(_callback)_callback(out,err);
setTimeout(closure,_interval);
});
});
return closure;
}
//now make a closure for every call to this function
var functRef = callLater(interval,commandString,callback);
//the first call
functRef();
}
It becomes easier to reason about if you separate things up a bit.
For example, the repetition logic doesn't have to know about AJAX or callbacks at all:
function mkRepeater(interval, fn, fnScope, fnArgs) {
var running;
function repeat() {
if (!running) return;
fn.apply(fnScope, fnArgs);
setTimeout(repeat, interval);
}
return {
start: function() { running = true; repeat(); },
stop: function() { running = false; }
};
}
You can use it like this:
var r = mkRepeater(2000, ajaxFunction, this, ["getStuff", callbackFn]);
r.start();
...
r.stop();

Variables set during $.getJSON function only accessible within function

This may be more of a scoping question. I'm trying to set a JSON object within a $.getJSON function, but I need to be able to use that object outside of the callback.
var jsonIssues = {}; // declare json variable
$.getJSON("url", function(data) {
jsonIssues = data.Issues;
});
// jsonIssues not accessible here
A similar question like this one was asked in another post, and the consensus was that anything I need to do with the JSON objects needs to be done within the callback function, and cannot be accessed anywhere else. Is there really no way that I can continue to access/manipulate that JSON object outside of the $.getJSON callback? What about returning the variable, or setting a global?
I'd appreciate any help. This just doesn't seem right...
UPDATE:
Tried setting the $.ajax() async setting to false, and running through the same code, with no luck. Code I tried is below:
var jsonIssues = {}; // declare json variable
$.ajax({ async: false });
$.getJSON("url", function(data) {
jsonIssues = data.Issues;
});
// jsonIssues still not accessible here
Also, I've had a couple responses that a global variable should work fine. I should clarify that all of this code is within $(document).ready(function() {. To set a global variable, should I just declare it before the document.ready? As such:
var jsonIssues = {};
$(document).ready(function() {
var jsonIssues = {}; // declare json variable
$.getJSON("url", function(data) {
jsonIssues = data.Issues;
});
// now accessible?
}
I was under the impression that that a variable declared within document.ready should be "globally" accessible and modifiable within any part of document.ready, including subfunctions like the $.getJSON callback function. I may need to read up on javascript variable scoping, but there doesn't seem to be an easy to achieve what I'm going for. Thanks for all the responses.
UPDATE #2:
Per comments given to answers below, I did use $.ajax instead of .getJSON, and achieved the results I wanted. Code is below:
var jsonIssues = {};
$.ajax({
url: "url",
async: false,
dataType: 'json',
success: function(data) {
jsonIssues = data.Issues;
}
});
// jsonIssues accessible here -- good!!
Couple follow-up comments to my answers (and I appreciate them all). My purpose in doing this is to load a JSON object initially with a list of Issues that the user can then remove from, and save off. But this is done via subsequent interactions on the page, and I cannot foresee what the user will want to do with the JSON object within the callback. Hence the need to make it accessible once the callback complete. Does anyone see a flaw in my logic here? Seriously, because there may be something I'm not seeing...
Also, I was reading through the .ajax() jQuery documentation, and it says that setting async to false "Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary."
Does anyone have an idea how I should be blocking user interaction while this is going on? Why is it such a concern? Thanks again for all the responses.
$.getJSON is asynchronous. That is, the code after the call is executed while $.getJSON fetches and parses the data and calls your callback.
So, given this:
a();
$.getJSON("url", function() {
b();
});
c();
The order of the calls of a, b, and c may be either a b c (what you want, in this case) or a c b (more likely to actually happen).
The solution?
Synchronous XHR requests
Make the request synchronous instead of asynchronous:
a();
$.ajax({
async: false,
url: "url",
success: function() {
b();
}
});
c();
Restructure code
Move the call to c after the call to b:
a();
$.getJSON("url", function() {
b();
c();
});
Remember that when you supply a callback function, the point of that is to defer the execution of that callback until later and immediately continue execution of whatever is next. This is necessary because of the single-threaded execution model of JavaScript in the browser. Forcing synchronous execution is possible, but it hangs the browser for the entire duration of the operation. In the case of something like $.getJSON, that is a prohibitively long time for the browser to stop responding.
In other words, you're trying to find a way to use this procedural paradigm:
var foo = {};
$.getJSON("url", function(data) {
foo = data.property;
});
// Use foo here.
When you need to refactor your code so that it flows more like this:
$.getJSON("url", function(data) {
// Do something with data.property here.
});
"Do something" could be a call to another function if you want to keep the callback function simple. The important part is that you're waiting until $.getJSON finishes before executing the code.
You could even use custom events so that the code you had placed after $.getJSON subscribes to an IssuesReceived event and you raise that event in the $.getJSON callback:
$(document).ready(function() {
$(document).bind('IssuesReceived', IssuesReceived)
$.getJSON("url", function(data) {
$(document).trigger('IssuesReceived', data);
});
});
function IssuesReceived(evt, data) {
// Do something with data here.
}
Update:
Or, you could store the data globally and just use the custom event for notification that the data had been received and the global variable updated.
$(document).ready(function() {
$(document).bind('IssuesReceived', IssuesReceived)
$.getJSON("url", function(data) {
// I prefer the window.data syntax so that it's obvious
// that the variable is global.
window.data = data;
$(document).trigger('IssuesReceived');
});
});
function IssuesReceived(evt) {
// Do something with window.data here.
// (e.g. create the drag 'n drop interface)
}
// Wired up as the "drop" callback handler on
// your drag 'n drop UI.
function OnDrop(evt) {
// Modify window.data accordingly.
}
// Maybe wired up as the click handler for a
// "Save changes" button.
function SaveChanges() {
$.post("SaveUrl", window.data);
}
Update 2:
In response to this:
Does anyone have an idea how I should be blocking user interaction while this is going on? Why is it such a concern? Thanks again for all the responses.
The reason that you should avoid blocking the browser with synchronous AJAX calls is that a blocked JavaScript thread blocks everything else in the browser too, including other tabs and even other windows. That means no scrolling, no navigation, no nothing. For all intents and purposes, it appears as though the browser has crashed. As you can imagine, a page that behaves this way is a significant nuisance to its users.
maybe this work, works to me.. :)
$variable= new array();
$.getJSON("url", function(data){
asignVariable(data);
}
function asignVariable(data){
$variable = data;
}
console.log($variable);
Hope it help you..
:)
You could approach this with promises:
var jsonPromise = $.getJSON("url")
jsonPromise.done(function(data) {
// success
// do stuff with data
});
jsonPromise.fail(function(reason) {
// it failed... handle it
});
// other stuff ....
jsonPromise.then(function(data) {
// do moar stuff with data
// will perhaps fire instantly, since the deferred may already be resolved.
});
It is pretty straight forward and a viable way to make async code feel more imperative.
"But this is done via subsequent interactions on the page, and I cannot foresee what the user will want to do with the JSON object within the callback."
The callback is your opportunity to set the screen up for the user's interaction with the data.
You can create or reveal HTML for the user, and set up more callbacks.
Most of the time, none of your code will be running. Programming an Ajax page is all about thinking about which events might happen when.
There's a reason it's "Ajax" and not "Sjax." There's a reason it's a pain to change from async to sync. It's expected you'll do the page async.
Event-driven programming can be frustrating at first.
I've done computationally intensive financial algorithms in JS. Even then, it's the same thing--you break it up into little parts, and the events are timeouts.
Animation in JavaScript is also event driven. In fact, the browser won't even show the movement unless your script relinquishes control repeatedly.
You are just running into scoping issues.
Short answer:
window.jsonIssues = {}; // or tack on to some other accessible var
$.getJSON("url", function(data) {
window.jsonIssues = data.Issues;
});
// see results here
alert(window.jsonIssues);
Long answers:
Scoping issue in Javascript
Javascript closure scoping issue

Categories

Resources