Reputation: 3374
I am trying to create a JavaScript object that will deal with all of my ajax calls instead of making several different ajax handlers have one that does the job for all.
So here's what I have so far
My PHP files that are going to be called within my AJAX Handler are placed in a directory called ajax, the directories within that are named to relate to the pages e.g. the jobs page has its own directory and so on. within these directories I have placed the page relevant PHP files.
so now to my ajax Handler object code:
function ajaxHandler(pageName,functionCall){
this.pageName = pageName;
this.functionCall = functionCall;
// set functions
this.getPage = getPage;
this.setPage = setPage;
this.getFunctionCall = getFunctionCall;
this.setFunctionCall = setFunctionCall;
this.performAjaxCall = performAjaxCall;
}
// accessor for current page
function getPage(){
return this.pageName;
}
// accessor for setting the current page
function setPage(page){
this.pageName = page;
}
// accessor for retrieving the current functionCall
function getFunctionCall(){
return this.functionCall;
}
// accessor for setting the current function call
function setFunctionCall(func){
this.functionCall = func;
}
// perform the loaded ajax call
// DATA : must be in the form of JSON
function performAjaxCall(data){
$.ajax({
type : 'POST',
url : '/ajax/'+ this.pageName + '/' + this.functionCall + '.php',
dataType : 'json',
data : data,
success : function(data){
return data;
},
error : function(xhr, ajaxOptions, thrownError){
return {"error":true,"msg":thrownError};
}
})
}
so with this file called and working fine, apart from when performAjaxCall is called the ajax works perfectly but the data being returned is being seen as undefined I will show you an example
function getActiveJobs(initPage){
var ajh = new ajaxHandler('jobs','getActiveJobs');
var req = {'page' : 1};
var data = ajh.performAjaxCall(req);
alert(data.error);
}
The alert returns undefined, I suspect it is because the JavaScript is not waiting for the data to be returned and as such data is not yet defined, but I am unsure I thought I would ask here before leading myself down a blind alley.
Upvotes: 1
Views: 178
Reputation: 816462
You are right, JavaScript is not waiting. performAjaxCall
returns before the response of request is received. But even it were waiting, you cannot return a value from a callback like this:
success : function(data){
return data;
},
You are passing this function to $.ajax
, so it returns ne value only inside the $.ajax
function. It does not have any effect on the outer performAjaxCall
function.
You have to pass another function which will process the data, something like:
function performAjaxCall(data, cb){
$.ajax({
//...
success: cb,
error: cb
});
}
and
function getActiveJobs(initPage){
var ajh = new ajaxHandler('jobs','getActiveJobs');
var req = {'page' : 1};
ajh.performAjaxCall(req, function(data) {
alert(data.error);
});
}
Upvotes: 2