Creating callbacks with Javascript - javascript

Alright, so I'm a little confused on how to create callbacks in JavaScript and a mix of jQuery.
Here's what I'd like to do:
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
}
});
}
The reason I want to do this is to be able to re-use this function and having a different "loading" message for what I need it for. In other words, the scenario would look like this:
$('div#job').html('loading...');
saveArtDep('job_id=3&update_art=true', function(){
$('div#job').html('success!');
});
Any help would be great!

In saveArtDep the parameter callback refers to a function, so you can invoke it using callback()
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
callback();
}
});
}

You almost had it. You can pass anything to callback and we make sure that it is a function before executing it, in the below seen code.
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
if (typeof callback === 'function') {
callback();
}
}
});
}

success: function(data) {
if(typeof callback == 'function') {
callback(data);
}
}

Related

Ajax Jquery run a function then with ajax inside and return success data

var datatobeuse = SearchTable("user_tbl", "first_name", "fname", "last_name", "lname");
I have this above code right after document ready.Then I have below code after document ready
function SearchTable(tablename, column1, label1, column2, label2) {
$.ajax({
type: 'POST',
url: '..user.php',
data: {
tablename: tablename,
column1: column1,
label1: label1,
column2: colum2,
label2: label2,
},
dataType: "json",
success: function (data) {
// console.log(JSON.stringify(data))
},
error: function (data) {
}
}).done(function (data) {
});
}
How can I use the data in success? I need to have return value so that I can use var datatobeuse which is right after document ready.
I tried solution from here
Like this one :
function isSession(selector) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// Call this function on success
someFunction( data );
return data;
},
error: function() {
alert('Error occured');
}
});
}
function someFunction( data ) {
// Do something with your data
}
But it is not working
What you should do, is embrace the asynchronous character of javascript.
Asynchronous means it takes some time to execute the function, the rest of the javascript stuff will not wait for it. Ajax is an exellent example of this.
The solution is the callback. A callback is a function that will be called when the rest of the functionnality is ready.
I'll take your example to explain.
function isSession(selector, onReady) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// all is finished. Now we can call the callback
if(typeof onReady == 'function') {
onReady(data);
}
},
error: function() {
}
});
}
function someFunction( data ) {
// Do something with your data
}
// now use them both
var selector = ".links";
isSession(selector, function(data) {
someFunction( data );
});
Reconsider why exactly you asked this question. You don't need a return value for your function.
This takes some different thinking. You wanted to know how to set the values to datatobeuse, like this:
var datatobeuse = somefunction();
// now datatobeuse is ready and we can use it.
displayOnScreen(datatobeuse);
Instead, think this way
var datatobeuse;
somefunction(function(data) {
datatobeuse = data;
displayOnScreen(datatobeuse);
})

$.ajax + make success function parameterized

A stupid question.
I am calling $.ajax function in many of my button clicks, text changed, drop down value changed etc. So I thought of making this function parameterized. Below is the code I was trying to use.
function ajaxCall(ajaxUrl, methodName) {
try {
$.ajax({
type: 'POST',
url: ajaxUrl,
success: methodName
},
dataType: "html"
});
}
catch (e) {
alert(e.message);
}
}
In this the "methodName" should be the name of the method the control should go.
Or in short, when I use ajaxCall('test.aspx','testMethod'), the control should be transferred to
function testMethod(xmlResponse){
alert ('Inside testMethod');
}
In JavaScript you can use functions as variables, so just call ajaxCall with url and success handler.
function testMethod (xmlResponse) {
alert('Inside testMethod');
}
function ajaxCall (ajaxUrl, methodName) {
try {
$.ajax({
url: ajaxUrl,
type: 'POST',
dataType: 'html',
success: methodName
});
}
catch (e) {
alert(e.message);
}
}
ajaxCall('test.aspx', testMethod);

How to write a jQuery function with a callback that you can pass Params to?

I have the following function:
function loadProjects(pID) {
$.ajax({
url: myURL,
success: function (dataJS) {###Run any supplied call back here####}
});
}
I call this function like so loadProjects(1);
Issue is I want to be able to define a callBack function after success, and I'd like to include it when I do loadProjects(1, pong(12)). I want to be able to supply params to the callback.
How can I have a function accept a callback?
How can I pass a callback to that function?
Something like
function loadProjects(pID, callback) {
$.ajax({
url: myURL,
success: function (dataJS) {###Run any supplied call back here####}
});
}
Where I could then call:
loadProjects(22, pong(12))
Problem is when I try this, pong(12) is running immediately, and not later when called in the loadProjects function?
Ideas? Thanks
try this:
function loadProjects(pID, callback) {
$.ajax({
url: myURL,
success: function (dataJS) {
if ($.isFunction(callback))
callback();
}
});
}
loadProjects(1, function() { pong(12); });
or:
function loadProjects(pID, callback, value) {
$.ajax({
url: myURL,
success: function (dataJS) {
if ($.isFunction(callback)) {
if (value) {
callback(value);
}else{
callback();
}
}
}
});
}
loadProjects(1, pong, 12);
loadProjects(22, function(){pong(12);});
Try something like this:
var loadProjects = (function(pID, callback) {
var params = { "property" : "value" }
$.ajax({
url: myURL,
success: function (dataJS) { callback(params); }
});
})
loadProjects(22, function(p){ console.log(p); });
function loadProjects(pID, callback) {
var callbackArgs = arguments;
callbackArgs.shift();
callbackArgs.shift();
$.ajax({
url: myURL,
success: function (dataJS) {
// Null or this can be used depending on desired behavaiour
// See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply
callback.apply(null, callbackArgs);
}
});
}
Example usage:
loadProjects(22, pong, 12);
loadProjects(22, pong, 12, 'foo', 'bar');
12, foo, and bar are all passed to the pong callback.

problems executing a jquery ajax call within a function

I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}

Promote callback onSuccess return value to the Caller Function return value

I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.
A super-simplified version of the generic function without all my logic would be:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
return true;
else
return false;
},
error:
function(errorThrown) {
return false;
}
});
}
And the function calling it would be something like:
function Next() {
var result = CallServer("/Signum/TrySave");
if (result == true) {
document.forms[0].submit();
}
}
The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.
Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?
Thanks
Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:
function CallServer(urlController, callback) {
$.ajax({
type: "POST",
url: urlController,
async: true,
data: $("form").serialize(),
success:
function(result) {
var ret = ( someLogic );
callback(ret);
},
error:
function(errorThrown) {
return false;
}
});
}
function Next() {
CallServer("/Signum/TrySave", function(result) {
if (result == true) {
document.forms[0].submit();
}
});
}
I usually put any code to be executed on success inside the callback function itself. I don't think CallServer() actually receives the return values from the callbacks themselves.
Try something like:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
document.forms[0].submit();
else
// do something else
},
error:
function(errorThrown) {
// handle error
}
});
}
Edit: I'm not too familiar with jQuery, so I might be completely wrong (I'm basing this on the behavior of other frameworks, like YUI, and AJAX calls made without any framework). If so, just downvote this answer and leave a comment, and I will delete this answer.
Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Afterwards I can return that variable. I place the code for future readers:
function CallServer(urlController) {
var returnValue = false;
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic){
returnValue = true;
return;
}
},
error:
function(errorThrown) {
alert("Error occured: " + errorThrown);
}
});
return returnValue;
}

Categories

Resources